Newbie :
Let say I have a class ClassA, and it has ClassB as its attribute:
public ClassA
{
private String attr;
private ClassB classB;
}
public ClassB
{
private String attr1;
private int attr2;
}
From the class above, is it possible to sort the list of ClassA List<ClassA> list
by attribute of ClassB using Comparator
? It can be sort by the ClassA attribute easily by the code Comparator.comparing(ClassA::getAttr)
, but what if I want to sort the list by the attribute in ClassB
, let say the attr2
attribute?
Ravindra Ranwala :
You can do it like so,
List<ClassA> sortedList = list.stream()
.sorted(Comparator.comparing(a -> a.getClassB().getAttr2()))
.collect(Collectors.toList());
Pass the comparing Function
to the Comparator
and it will create a new stream
sorted according to the given Comparator
. Then collect it into a List
.
If you want to handle null values, it can be done like below.
final List<ClassA> sortedList = list.stream()
.sorted(Comparator.nullsFirst(
Comparator.comparing(a -> a.getClassB().getAttr1(), Comparator.nullsLast(String::compareTo))))
.collect(Collectors.toList());