-1

I want to sort my list of objects. I want to compare the Attribute elements by their names and compare the integer variable number of each object.

Below there is my code. I commented the line which doesn't work. How can I sort by the variable name of the non-primitive attribute Attribute of my Object?

List<Object> objects
List<Object> sortedObjects = objects.stream()
          .sorted(Comparator.comparing(Object::getAtt().getName)) //this doesn't work.
          .sorted(Comparator.comparing(Object::getNumber))
          .collect(Collectors.toList());

public class Object {
    Attribute att;
    int number;
    
    public Attribute getAtt() {
        return att;
    }
    public int getNumber() {
        return number;
    }

}

public class Attribute {
    String name;

    public String getName() {
        return name;
    }

}
2
  • :: denotes a method reference. You can only place a single name after it, not code. As rzwitserloot said, use a lambda if you want code. Commented Mar 8, 2021 at 11:41
  • This question is similar to: Java Method reference not expected here. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jan 9 at 20:16

2 Answers 2

2

Object::getAtt().getName

This isn't a thing. o -> o.getAtt().getName() is what you're looking for, I think.

Sign up to request clarification or add additional context in comments.

Comments

0

In addition to the compilation problem that Object::getAtt().getName should instead be o -> o.getAtt().getName() (addressed by this answer), the sorting is not implemented correctly.

By having two different sorted operations on the stream, the second sort operation will override the first (except in cases where the second operation yields a tie, in which case the first sort's relative ordering will be retained). It would be better to have a single sorted operation that sorts all elements as desired:

List<Object> sortedObjects = objects.stream()
        .sorted(Comparator.<Object, String>comparing(o -> o.getAtt().getName())
                .thenComparing(Object::getNumber))
        .collect(Collectors.toList());

Comments

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.