Sort an array of objects by one property of a nested object

I need to compare an array of objects by one property of one of the properties of its objects.
I do:

List<Sell> collect = sells.stream()
        .sorted(Comparator.comparing(Sell::getClient.name, String::compareToIgnoreCase))
        .collect(Collectors.toList());

Does not compile, no one knows how to do this?

Thanks.

+4
source share
2 answers

This is part of the error code.

Sell::getClient.name

You can create a link to a (static or non-static) method of an arbitrary object of a certain type. A reference to the method of getClientany type object is Sellas follows:

Sell::getClient

But method references are not objects and have no members to access. With this code, you are trying to access a member variable of a link (and cannot)

Sell::getClient.name

, , . - , :

Sell::getClient::getName

@mlk:

  • x -> x.getClient().name
  • Sell::getClientName ( )
+3

, . .

,

class Test {

    // I assume that Client looks like this.
    static class Client {
        public String name;
    }

    // And that Sell looks like this.
    // I'm sure your Client and Sell are bigger, but this is all 
    // that matters for now. 
    static class Sell {
        public Client getClient() { return null; }
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        List<Sell> sells = new ArrayList<>();
        sells.stream().sorted(Comparator.comparing(x -> x.getClient().name, String::compareToIgnoreCase))
    }
}

, .

:

static class Sell {
    public String getClientName() { return null; }
}
// ...
        sells.stream().sorted(Comparator.comparing(Sell::getClientName, String::compareToIgnoreCase))
0

Source: https://habr.com/ru/post/1616185/


All Articles