Comparator.comparing to sort a list using nested object's field

Jacob :

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=355419&siteId=1