按照嵌套对象中的一个属性对对象数组进行排序

9

我需要比较对象数组中某个对象的属性值。
我的代码如下:

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

编译不通过,有人知道怎么解决吗?

谢谢。


什么是错误?Shell.getClient看起来像什么? - Michael Lloyd Lee mlk
什么是Sell,Client类定义?你正在使用流的销售情况是什么?请提供完整的代码。 - Dev
如果你想要一个不区分大小写的Comparator,可以使用String.CASE_INSENSITIVE_ORDERString::compareToIgnoreCase是一个返回整数而不是Comparator的比较方法。 - Manos Nikolaidis
它只是说找不到getClient.name。在Sell对象中,我有一个具有属性名称的Client对象。我觉得我无法使用此方法来处理嵌套对象的属性。 - user1260928
3个回答

8
这是导致错误的代码部分:
Sell::getClient.name 您可以创建特定类型任意对象(静态或非静态)方法的引用。任何 Sell 类型对象的 getClient 方法的引用如下所示:
Sell::getClient
但是,方法引用不是对象,没有成员可供访问。使用此代码,您正在尝试访问引用的成员变量(无法访问):
Sell::getClient.name 此外,方法引用不是类,因此您无法从中获取另一个方法引用。如果您尝试这样做,则会失败:
Sell::getClient::getName @mlk 提供了适用于您特定情况的正确语法:
1. x -> x.getClient().name 2. Sell::getClientName(不必是静态方法)

3
为了访问嵌套属性并按相反顺序排序,我正在进行以下操作:
Comparator<Sell> comparator = Comparator.comparing(h -> h.getAudit().getCreatedTs());
    sells.sort(comparator.reversed());

这是我让它工作的唯一方法:我尝试过 Sell.sort((Comparator.comparing(x -> x.getAudit().getCreatedTs()).reversed()); 但是一直出现reversed方法错误。 - FleaLes

1

我看不到你的代码,也看不到你遇到的错误。所以这只是一个猜测。

我认为你想要

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

我对大部分内容表示赞同。但是如果有一个像getClientName这样的方法可用,它就不必是静态的。根据教程,你可以获得“对特定类型的任意对象的实例方法的引用”。 - Manos Nikolaidis
啊,好的,我修正了我的回答。 - Michael Lloyd Lee mlk

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接