Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...