Java – Sort using Streams

 

package com.pwn.stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortUsingStream {

	public static void main(String[] args) {
		List<String> data = new ArrayList<>();
		data.add("New York");
		data.add("New York");
		data.add("Amsterdam");
		data.add("Mumbai");
		data.add("California");
		System.out.println("original List" + data);
		List<String> sortedList = data.stream().sorted()
				.collect(Collectors.toList());

		System.out.println(
				"Sorted List using stream sort() " + sortedList);

		List<String> sortedList2 = data.stream()
				.sorted((s1, s2) -> s1.compareTo(s2))
				.collect(Collectors.toList());
		System.out.println("Sorted List using compareTo() operator "
				+ sortedList2);

		List<String> reverseSortedList = data.stream()
				.sorted(Comparator.reverseOrder())
				.collect(Collectors.toList());

		System.out.println("Reverse sort " + reverseSortedList);

	}

}



[New York, New York, Amsterdam, Mumbai, California]
Sorted List using stream sort() [Amsterdam, California, Mumbai, New York, New York]
Sorted List using compareTo() operator [Amsterdam, California, Mumbai, New York, New York]
Reverse sort [New York, New York, Mumbai, California, Amsterdam]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s