Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects by one property of nested object

Tags:

java

arrays

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.

like image 991
user1260928 Avatar asked Nov 17 '15 09:11

user1260928


People also ask

How do you sort an array of objects by property?

To sort an array of objects in JavaScript, use the sort() method with a compare function. A compare function helps us to write our logic in the sorting of the array of objects. They allow us to sort arrays of objects by strings, integers, dates, or any other custom property.

Can we sort array of objects?

Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.


1 Answers

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)
like image 74
Manos Nikolaidis Avatar answered Sep 24 '22 15:09

Manos Nikolaidis