Java 要按每个唯一列的最大值过滤的流
Java Stream to Filter by max value for each unique column
我有一个这样的列表
[
{
"applicationNumber": "100400",
"points":"20"
},
{
"applicationNumber": "100400",
"points": "100"
},
{
"applicationNumber": "200543",
"points": "54"
},
{
"applicationNumber": "200543",
"points": "23"
},
{
"applicationNumber": "243543",
"points":"53"
}
]
存储在变量'list'
对于每个 applicationNumber,我想要最大分数并忽略列表中的所有剩余分数。
我想使用 Java Streams 实现同样的效果。谁能帮帮我
我正在使用的当前代码,但没有得到结果。
List<MyClassPOJO> list = someFunction();
List<MyClassPOJO> filteredOutput =
list.stream().max(Comparator.comparing(MyClassPOJO::getPoints)).orElse(null);
使用此代码,我无法获得函数 getPoints 并过滤我的数据。我可以使用 for 循环来做到这一点。
PS: 先谢谢你了。
你可以先按你的applicationNumber
进行分组,然后从每组中取出得分最高的元素
List<MyClassPOJO> filteredOutput =
list.stream()
.collect(Collectors.groupingBy(MyClassPOJO::getApplicationNumber,
Collectors.maxBy(Comparator.comparing(MyClassPOJO::getPoints))))
.values().stream()
.map(Optional::get)
.collect(Collectors.toList());
我有一个这样的列表
[
{
"applicationNumber": "100400",
"points":"20"
},
{
"applicationNumber": "100400",
"points": "100"
},
{
"applicationNumber": "200543",
"points": "54"
},
{
"applicationNumber": "200543",
"points": "23"
},
{
"applicationNumber": "243543",
"points":"53"
}
]
存储在变量'list'
对于每个 applicationNumber,我想要最大分数并忽略列表中的所有剩余分数。
我想使用 Java Streams 实现同样的效果。谁能帮帮我
我正在使用的当前代码,但没有得到结果。
List<MyClassPOJO> list = someFunction();
List<MyClassPOJO> filteredOutput =
list.stream().max(Comparator.comparing(MyClassPOJO::getPoints)).orElse(null);
使用此代码,我无法获得函数 getPoints 并过滤我的数据。我可以使用 for 循环来做到这一点。
PS: 先谢谢你了。
你可以先按你的applicationNumber
进行分组,然后从每组中取出得分最高的元素
List<MyClassPOJO> filteredOutput =
list.stream()
.collect(Collectors.groupingBy(MyClassPOJO::getApplicationNumber,
Collectors.maxBy(Comparator.comparing(MyClassPOJO::getPoints))))
.values().stream()
.map(Optional::get)
.collect(Collectors.toList());