Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting using Comparator Interface and java 8 Streams

Tags:

Parent is a class which is inherited by Child. which is inherited by GrandChild. Each class contains List of the child class(i.e Parent contains List of Child and Child contains List of GrandChild). Each class contains 50 attributes(attrib1-atrib50). getChildList() returns the arrayList of objects of type Child getGrandChildList() returns the arrayList of objects of type GrandChild

Let resultSet be List of Parent

List<Parent> resultSet 

Now I want to sort the list based on some attributes. For example if I want to sort resultSet based on two parent attributes(say Attribute 1 and attribute 2, I use this code.

Comparator<Parent> byFirst = (e1, e2) -> e2.getAttrib1().compareTo(e1.getAttrib1()); Comparator<Parent> bySecond = (e1, e2) -> e1.getAttrib2().compareTo(e2.getAttrib2());  Comparator<Parent> byThird = byFirst.thenComparing(bySecond);   List<Parent> sortedList = resultSet.stream().sorted(byThird).collect(Collectors.toList()); 

Now I want to sort the parentlist based on attribute 1 of Child class and attribute 1 of GrandChild class. How should I sort this.

like image 846
Manu Joy Avatar asked Apr 30 '15 09:04

Manu Joy


People also ask

Which sorting algorithm is used by Comparator in Java?

The Comparator and Comparable interface don't do any sorting, so there is no sorting algorithm there. They just compare two Objects, something you need if you want to sort a list of those objects.

How do you sort an employee object in Java 8 based on salary?

In order to sort Employee object on different criteria, we need to create multiple comparators e.g. NameComparator, AgeComparator, and SalaryComparator, this is known as custom sorting in Java. This is different from the natural ordering of objects, provided by the compareTo() method of java. lang.


1 Answers

Use Comparator.comparing to make the comparators. Just figure out what you want to compare. It will looks something like this, except you will write whatever logic you want to use to extract the values to compare:

Comparator<Parent> byAttr1ofFirstChild = Comparator.comparing(     parent -> parent.getChildren().get(0).getAttr1() );  Comparator<Parent> byAttr1ofFirstGrandChild = Comparator.comparing(     parent -> parent.getChildren().get(0).getGrandChildren().get(0).getAttr1() );   List<Parent> sortedList = parents.stream()     .sorted(byAttr1ofFirstChild.thenComparing(byAttr1ofFirstGrandChild))     .collect(toList()); 

Comparator.comparing would also make the examples in your question much nicer (using static imports) :

Comparator<Parent> byFirst = comparing(Parent::getAttrib1, reverseOrder()); Comparator<Parent> bySecond = comparing(Parent::getAttrib2); 
like image 117
Misha Avatar answered Sep 29 '22 15:09

Misha