The Sort
method defined in the Stream
class is used to sort
the jumbled elements, Sort
is an intermediate
operation ie it takes a stream
of input, sorts it and passes it on to the next intermediate
or terminal
operator. The sort
function is stateful
in nature, ie it needs the state of previous elements while computing current.
The Collections sort method will modify the original Collection, whereas the stream will return a new sorted Collection without changing the actual Collection.
package org.wesome.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
class Apple {
public static void main(String args[]) {
List<Integer> integers = Arrays.asList(10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
List<Integer> tempIntegers = new ArrayList<>(integers);
System.out.println("*---------------------------Traditional method---------------------------*");
Collections.sort(tempIntegers);
System.out.println(tempIntegers);
System.out.println("*---------------------------Sorted---------------------------*");
integers.stream().sorted().forEach(System.out::println);
integers.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);
}
}
Sorting in Reverse Order
package org.wesome.java8;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
class Apple {
public static void main(String args[]) {
List<Integer> integers = Arrays.asList(10, 9, 8, 7, 6, 5, 4, 3, 2, 1);
List<Integer> tempIntegers = new ArrayList<>(integers);
System.out.println("*---------------------------Traditional method---------------------------*");
Collections.sort(tempIntegers, Comparator.reverseOrder());
System.out.println(tempIntegers);
System.out.println("*---------------------------Sorted---------------------------*");
integers.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
integers.stream().sorted((i1, i2) -> i2.compareTo(i1)).forEach(System.out::println);
}
}
Sort Map Key
package org.wesome.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Apple {
public static void main(String args[]) {
Map<Integer, String> map = new HashMap();
map.put(4, "Jonagold");
map.put(3, "Gala");
map.put(2, "Fuji");
map.put(1, "Macintosh");
System.out.println("*---------------------------Traditional method---------------------------*");
List<Integer> list = new ArrayList<>(map.keySet());
Collections.sort(list);
for (Integer integer : list) {
System.out.println(integer + " " + map.get(integer));
}
System.out.println("*---------------------------Sorted---------------------------*");
map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach(System.out::println);
}
}
Sort Map Key In reverse Order
package org.wesome.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Apple {
public static void main(String args[]) {
Map<Integer, String> map = new HashMap();
map.put(4, "Jonagold");
map.put(3, "Gala");
map.put(2, "Fuji");
map.put(1, "Macintosh");
System.out.println("*---------------------------Traditional method---------------------------*");
List<Integer> list = new ArrayList<>(map.keySet());
Collections.sort(list, Comparator.reverseOrder());
for (Integer integer : list) {
System.out.println(integer + " " + map.get(integer));
}
System.out.println("*---------------------------Sorted---------------------------*");
map.entrySet().stream().sorted(Map.Entry.<Integer, String>comparingByKey().reversed()).forEach(System.out::println);
}
}
Sort by Map Value
package org.wesome.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
class Apple {
public static void main(String args[]) {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(4, "Jonagold");
map.put(3, "Gala");
map.put(2, "Fuji");
map.put(1, "Macintosh");
System.out.println("*---------------------------Traditional method---------------------------*");
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
List<Map.Entry<Integer, String>> arrayList = new ArrayList(entrySet);
Collections.sort(arrayList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));
map.clear();
for (Map.Entry<Integer, String> entry : arrayList) {
map.put(entry.getKey(), entry.getValue());
}
System.out.println("map = " + map);
System.out.println("*---------------------------Sorted---------------------------*");
map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);
}
}
Sort By Map Value in reverse order
package org.wesome.java8;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
class Apple {
public static void main(String args[]) {
Map<Integer, String> map = new LinkedHashMap<>();
map.put(4, "Jonagold");
map.put(3, "Gala");
map.put(2, "Fuji");
map.put(1, "Macintosh");
System.out.println("*---------------------------Traditional method---------------------------*");
Set<Map.Entry<Integer, String>> entrySet = map.entrySet();
List<Map.Entry<Integer, String>> arrayList = new ArrayList(entrySet);
Collections.sort(arrayList, (o1, o2) -> o2.getValue().compareTo(o1.getValue()));
map.clear();
for (Map.Entry<Integer, String> entry : arrayList) {
map.put(entry.getKey(), entry.getValue());
}
System.out.println("map = " + map);
System.out.println("*---------------------------Sorted---------------------------*");
map.entrySet().stream().sorted(Map.Entry.<Integer, String>comparingByValue().reversed()).forEach(System.out::println);
}
}
Sort Map of User-Defined Object based on the value of Object in the natural order.
package org.wesome.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Data
@AllArgsConstructor
class Fruit {
int fruitId;
String fruitName;
int price;
public static void main(String[] args) {
Map<String, Fruit> appleMap = new LinkedHashMap<>();
appleMap.put("Macintosh", new Fruit(1, "Macintosh", 3));
appleMap.put("Fuji", new Fruit(2, "Fuji", 1));
appleMap.put("Gala", new Fruit(3, "Gala", 4));
appleMap.put("Jonagold", new Fruit(4, "Jonagold", 2));
Map<String, Fruit> tempAppleMap = new LinkedHashMap<>(appleMap);
System.out.println("*---------------------------Traditional method---------------------------*");
Set<Map.Entry<String, Fruit>> entrySet = appleMap.entrySet();
List<Map.Entry<String, Fruit>> arrayList = new ArrayList(entrySet);
Collections.sort(arrayList, (o1, o2) -> o1.getValue().getPrice() - o2.getValue().getPrice());
appleMap.clear();
for (Map.Entry<String, Fruit> entry : arrayList) {
appleMap.put(entry.getKey(), entry.getValue());
}
System.out.println("appleMap = " + appleMap);
System.out.println("*---------------------------Sorted method---------------------------*");
tempAppleMap.entrySet().stream().sorted(Comparator.comparingInt(value -> value.getValue().getPrice())).forEach(System.out::println);
}
}
Sort Map of User-Defined Object based on the value of Object in the reverse order.
package org.wesome.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Data
@AllArgsConstructor
class Fruit {
int fruitId;
String fruitName;
int price;
public static void main(String[] args) {
Map<String, Fruit> appleMap = new LinkedHashMap<>();
appleMap.put("Macintosh", new Fruit(1, "Macintosh", 3));
appleMap.put("Fuji", new Fruit(2, "Fuji", 1));
appleMap.put("Gala", new Fruit(3, "Gala", 4));
appleMap.put("Jonagold", new Fruit(4, "Jonagold", 2));
Set<Map.Entry<String, Fruit>> entrySet = appleMap.entrySet();
List<Map.Entry<String, Fruit>> arrayList = new ArrayList(entrySet);
Collections.sort(arrayList, (o1, o2) -> o2.getValue().getPrice() - o1.getValue().getPrice());
for (Map.Entry<String, Fruit> entry : arrayList) {
System.out.println("salaryMap = " + entry.getKey() + " " + entry.getValue());
}
}
}
Sort User Defined Objects
package org.wesome.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@Data
@AllArgsConstructor
class Fruit {
int fruitId;
String fruitName;
}
class FruitIdComparator implements Comparator<Fruit> {
@Override
public int compare(Fruit o1, Fruit o2) {
return o1.getFruitId() - o2.getFruitId();
}
}
class Apple {
public static void main(String args[]) {
List<Fruit> fruits = Arrays.asList(new Fruit(4, "Macintosh"), new Fruit(3, "Fuji"), new Fruit(2, "Gala"), new Fruit(1, "Jonagold"));
List<Fruit> tempFruits = new ArrayList<>(fruits);
System.out.println("*---------------------------Traditional method---------------------------*");
Collections.sort(tempFruits, new FruitIdComparator());
System.out.println(tempFruits);
System.out.println("*---------------------------Sorted using inline comparator---------------------------*");
fruits.stream().sorted((o1, o2) -> o1.getFruitId() - o2.getFruitId()).forEach(System.out::println);
System.out.println("*---------------------------Sorted using Generic Comparing method---------------------------*");
fruits.stream().sorted(Comparator.comparing(Fruit::getFruitId)).forEach(System.out::println);
System.out.println("*---------------------------Sorted using Int Comparing method---------------------------*");
fruits.stream().sorted(Comparator.comparingInt(Fruit::getFruitId)).forEach(System.out::println);
}
}
Sort User Defined Object in Reverse Order
package org.wesome.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@Data
@AllArgsConstructor
class Fruit {
int fruitId;
String fruitName;
}
class FruitIdComparator implements Comparator<Fruit> {
@Override
public int compare(Fruit o1, Fruit o2) {
return o2.getFruitId() - o1.getFruitId();
}
}
class Apple {
public static void main(String args[]) {
List<Fruit> fruits = Arrays.asList(new Fruit(4, "Macintosh"), new Fruit(3, "Fuji"), new Fruit(2, "Gala"), new Fruit(1, "Jonagold"));
List<Fruit> tempFruits = new ArrayList<>(fruits);
System.out.println("*---------------------------Traditional method---------------------------*");
Collections.sort(tempFruits, new FruitIdComparator());
System.out.println(tempFruits);
System.out.println("*---------------------------Sorted using inline comparator---------------------------*");
fruits.stream().sorted((o1, o2) -> o2.getFruitId() - o1.getFruitId()).forEach(System.out::println);
System.out.println("*---------------------------Sorted using Generic Comparing method---------------------------*");
fruits.stream().sorted(Comparator.comparing(Fruit::getFruitId, Comparator.reverseOrder())).forEach(System.out::println);
}
}
Comparator Chaining
Java allows chaining multiple comparators together to sort on multiple criteria.
package org.wesome.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@Data
@AllArgsConstructor
class Fruit {
int fruitId;
String fruitName;
int price;
}
class FruitIdComparator implements Comparator<Fruit> {
@Override
public int compare(Fruit o1, Fruit o2) {
return o1.getFruitId() - o2.getFruitId();
}
}
class FruitNameComparator implements Comparator<Fruit> {
@Override
public int compare(Fruit o1, Fruit o2) {
return o1.getFruitName().compareTo(o2.getFruitName());
}
}
class ComparatorChaining implements Comparator<Fruit> {
private List<Comparator<Fruit>> listComparators;
public void addComparator(Comparator<Fruit>... comparators) {
this.listComparators = Arrays.asList(comparators);
}
public int compare(Fruit empOne, Fruit empTwo) {
for (Comparator<Fruit> comparator : listComparators) {
int result = comparator.compare(empOne, empTwo);
if (result != 0) {
return result;
}
}
return 0;
}
}
class Apple {
public static void main(String args[]) {
List<Fruit> fruits = Arrays.asList(new Fruit(1, "Macintosh", 3), new Fruit(4, "Fuji", 1), new Fruit(2, "Gala", 2), new Fruit(1, "Jonagold", 4));
List<Fruit> tempFruits = new ArrayList<>(fruits);
System.out.println("*-----------Traditional method-----------*");
ComparatorChaining comparatorChain = new ComparatorChaining();
comparatorChain.addComparator(new FruitIdComparator());
comparatorChain.addComparator(new FruitNameComparator());
Collections.sort(tempFruits, comparatorChain);
System.out.println(tempFruits);
System.out.println("*-----------Comparator chaining-----------*");
fruits.stream().sorted(Comparator.comparing(Fruit::getFruitId).thenComparing(Fruit::getFruitName)).forEach(System.out::println);
}
}