我有一个 POJO 类
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;
}
}
id 是唯一的,但 groupName 不是。然后我就有了 A 的列表。
List<A> list = new ArrayList<A>();
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));
我想按 groupName 和值过滤列表,返回每个 groupName 的最大值。
List<B> filtedList = list....
//filtedList contain
//A(1, 'A', 3) A(3, 'B', 7) A(4, 'C', 7)
我知道我可以这样编码
Map<String, List<A>> map = list.stream().collect(
Collectors.groupingBy(A::getGroupName)
);
List<A> result = new ArrayList<A>();
map.forEach(
(s, a) -> {
result.addAll(
deliveryOrderItems.stream().sorted(
(o1, o2) -> o2.value.compareTo(o1.value)
).limit(1).collect(Collectors.toList())
);
}
);
问题是,我可以删除中间的 Map 并在一个链调用中进行这些操作吗
//list.stream().groupBy(A::getGroupName).orderInGroup(A::value).topInGroup(1)