我需要比较对象数组中某个对象的属性值。
我的代码如下:
List<Sell> collect = sells.stream()
.sorted(Comparator.comparing(Sell::getClient.name, String::compareToIgnoreCase))
.collect(Collectors.toList());
编译不通过,有人知道怎么解决吗?
谢谢。
Comparator<Sell> comparator = Comparator.comparing(h -> h.getAudit().getCreatedTs());
sells.sort(comparator.reversed());
Sell.sort((Comparator.comparing(x -> x.getAudit().getCreatedTs()).reversed());
但是一直出现reversed方法错误。 - FleaLes我看不到你的代码,也看不到你遇到的错误。所以这只是一个猜测。
我认为你想要
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
Comparator
,可以使用String.CASE_INSENSITIVE_ORDER
。String::compareToIgnoreCase
是一个返回整数而不是Comparator
的比较方法。 - Manos Nikolaidis