2

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()));
1
  • 1
    what do you mean not working? Commented Mar 28, 2020 at 19:06

1 Answer 1

1

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());
Sign up to request clarification or add additional context in comments.

2 Comments

I am seeing java.lang.UnsupportedOperationException: null at java.util.Collections$UnmodifiableList.sort(Collections.java:1331) for your answer @Naman
@Jacob that would rely on the type of List returned by your service.getTests call. If it's unmodifiable, the updated solution shall work for you. See the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.