按嵌套对象的一个​​属性对对象数组进行排序 [英] Sort array of objects by one property of nested object

查看:83
本文介绍了按嵌套对象的一个​​属性对对象数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要通过对象属性之一的一个属性来比较对象数组.
我在做:

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?

谢谢.

推荐答案

这是导致错误的代码部分

This is the part of the code that causes an error

Sell::getClient.name

您可以创建对特定类型任意对象的(静态或非静态)方法的引用.对Sell类型的任何对象的getClient方法的引用看起来像这样:

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

@mlk为您的特定情况提供了正确的语法:

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

  1. x -> x.getClient().name
  2. Sell::getClientName(不必是静态方法)
  1. x -> x.getClient().name
  2. Sell::getClientName (doesn't have to be a static method)

这篇关于按嵌套对象的一个​​属性对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆