Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (9.5k points)

Below is my code to sort resultSet based on two-parent attributes(Attribute 1 and attribute 2)

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());

Can anyone tell me how to sort the parentlist on the basis of attributes from the Child class and GrandChild class? 

1 Answer

0 votes
by (19.7k points)

You can use Comparator.comparing which makes comparators for any attributes which you want to compare. Check out the code below: 

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 helps you use static imports to code efficiently : 

Comparator<Parent> byFirst = comparing(Parent::getAttrib1, reverseOrder());

Comparator<Parent> bySecond = comparing(Parent::getAttrib2);

Interested in Java? Check out this Java tutorial by Intellipaat.    

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Apr 3, 2021 in Java by Jake (7k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...