Reputation: 420
I want to sort a list which looks like below based on a attribute of nested class.
class Test {
private NestedClass nestedClass;
private AnotherNested anotherNested;
private int id;
//getter, setter
}
class NestedClass {
private String field1;
private int field2;
// getter,setter
}
List<Test> tests = service.getTests(string something);
I want to sort tests by the field1
in nestedClass
using Comparator.comparing. I tried below which does not seem to be working
tests.stream().sorted(Comparator.comparing(test->test.getNestedClass().getField1()));
Upvotes: 2
Views: 2364
Reputation: 31898
You are calling sorted
API on a Stream
but not collecting the sorted stream into a List<Test>
further. No operation is performed whatsoever by the line of code you've used for the same reason.
To perform an in place operation, you should rather be calling sort
API on the List
interface as:
tests.sort(Comparator.comparing(test -> test.getNestedClass().getField1()));
Or else complete the stream operation collecting the data as a terminal operation as in :
List<Test> sortedTests = tests.stream()
.sorted(Comparator.comparing(test->test.getNestedClass().getField1()))
.collect(Collectors.toList());
Upvotes: 1