user1260928
user1260928

Reputation: 3439

Sort array of objects by one property of nested object

I need to compare an array of objects by one property of one of its objects property.
I am doing :

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

It's not compiling, doesn anyone know how to do?

Thanks.

Upvotes: 10

Views: 13319

Answers (3)

Sandeep
Sandeep

Reputation: 569

In order to access the nested property and sort in reversed order, I am doing as:

Comparator<Sell> comparator = Comparator.comparing(h -> h.getAudit().getCreatedTs());
    sells.sort(comparator.reversed());

Upvotes: 3

Michael Lloyd Lee mlk
Michael Lloyd Lee mlk

Reputation: 14661

I can't see your code, or the error you are getting. So this is a guess.

I believe you want

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))
    }
}

You want to call a method on the return of that, so you need to create an anonymous function.

Your other option would be:

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

Upvotes: 1

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22254

This is the part of the code that causes an error

Sell::getClient.name

Your can create a reference to a (static or non-static) method of an arbitrary object of a particular type. A reference to the getClient method of any object of Sell type looks like this :

Sell::getClient

But method references are not objects and don't have members to access. With this code you are trying to access a member variable of the reference (and can't)

Sell::getClient.name

Also, method references are not classes so you can't get another method reference from them. You couldn't do something like that if you tried :

Sell::getClient::getName

Correct syntax for your particular case was provided by @mlk :

  1. x -> x.getClient().name
  2. Sell::getClientName (doesn't have to be a static method)

Upvotes: 8

Related Questions