gpt4 book ai didi

Java 8 Lambda Sort 没有被调用

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:08:46 25 4
gpt4 key购买 nike

我有一个数据列表。我想使用自定义比较器进行排序。我有以下代码,但它没有被执行。你能告诉我哪里出了问题吗?

我尝试将 allACFs 数据类型设置为 java.util.Collection

List<Interface> allACFs =  (List<Interface>) SearchUtil.seacrh(individualiterator, SearchUtil.startswith("type.code", "ACF"));

allACFs.stream().sorted(new Comparator<Interface>() {

@Override
public int compare(Interface o1, Interface o2) {
System.out.println(o1.getType().getCode()+" : "+o2.getType().getCode()+" > "+o1.getType().getCode().compareTo(o2.getType().getCode()));
return o1.getType().getCode().compareTo(o2.getType().getCode());
}
});

最佳答案

您的自定义比较器未被调用,因为您没有从流中请求任何项目。因此,排序操作延迟直到您想要收获排序结果。

如果你想强制调用,在流上调用collect(Collectors.toList()):

List<Interface> list = allACFs.stream().sorted(new Comparator<Interface>() {
@Override
public int compare(Interface o1, Interface o2) {
System.out.println(o1.getType().getCode()+" : "+o2.getType().getCode()+" > "+o1.getType().getCode().compareTo(o2.getType().getCode()));
return o1.getType().getCode().compareTo(o2.getType().getCode());
}
}).collect(Collectors.toList());

关于Java 8 Lambda Sort 没有被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49641713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com