java call chain,May Java group& order& top in a call chain?

I have a POJO class

class A {

public int id;

public String groupName;

public String getGroupName() { return this.groupName; }

public int value;

public A(int id, String groupName, int value) {

this.id = id;

this.groupName = groupName;

this.value = value;

}

}

And id is Unique, but groupName is not. Then I have a List of A.

List list = new ArrayList();

list.add(new A(1, "A", 3));

list.add(new A(2, "B", 5));

list.add(new A(3, "B", 7));

list.add(new A(4, "C", 7));

I want filter the list by groupName and value, return the biggest value each groupName.

List filtedList = list....

//filtedList contain

//A(1, 'A', 3) A(3, 'B', 7) A(4, 'C', 7)

I knew that I can code like this

Map> map = list.stream().collect(

Collectors.groupingBy(A::getGroupName)

);

List result = new ArrayList();

map.forEach(

(s, a) -> {

result.addAll(

deliveryOrderItems.stream().sorted(

(o1, o2) -> o2.value.compareTo(o1.value)

).limit(1).collect(Collectors.toList())

);

}

);

And the question is, Can I remove the middle Map and do those operate in one chain call Like

//list.stream().groupBy(A::getGroupName).orderInGroup(A::value).topInGroup(1)

解决方案

What you can do is using groupingBy with a downstream collector.

In your case maxBy will do the job for you. This will give you a Map> where each key is mapped to an optional greatest value according to the comparator you supply.

Then you get the values of the map, filter them so that you only get non-empty optionals (avoiding a NSEE when calling get() on an Optional). You finally extract their content that you collect into a List.

import static java.util.Comparator.comparingInt;

import static java.util.stream.Collectors.groupingBy;

import static java.util.stream.Collectors.maxBy;

import static java.util.stream.Collectors.toList;

...

List resultList =

list.stream()

.collect(groupingBy(A::getGroupName,

maxBy(comparingInt(A::getValue))))

.values()

.stream()

.filter(Optional::isPresent)

.map(Optional::get)

.collect(toList());

Given your example, it outputs:

[A(1, A, 3), A(3, B, 7), A(4, C, 7)]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值