gpt4 book ai didi

Java 8 Stream API - 选择分组后的最低键

转载 作者:太空狗 更新时间:2023-10-29 22:43:30 26 4
gpt4 key购买 nike

我有一个 Foo 对象流。

class Foo {
private int variableCount;
public Foo(int vars) {
this.variableCount = vars;
}
public Integer getVariableCount() {
return variableCount;
}
}

我想要一个 Foo 的列表都是具有最低 variableCount 的。

例如

new Foo(3), new Foo(3), new Foo(2), new Foo(1), new Foo(1)

我只希望流返回最后 2 个 Foo s,因为它们的值最低。

我试过通过分组进行收集

.collect(Collectors.groupingBy((Foo foo) -> {
return foo.getVariableCount();
})

然后返回 Map<Integer, List<Foo>>而且我不确定如何将其转换为我想要的。

提前致谢

最佳答案

您可以使用排序映射进行分组,然后只获取第一个条目。沿线的东西:

Collectors.groupingBy(
Foo::getVariableCount,
TreeMap::new,
Collectors.toList())
.firstEntry()
.getValue()

关于Java 8 Stream API - 选择分组后的最低键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49014259/

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