如何合并Java流中的连续相似对象?
到现在为止,我还没有找到一个好的解决方案,因此希望您能提供帮助。
假设我们有一个类似以下的类:
class Someclass {
String type;
int count;
}
当具有流{“ a”,1},{“ a”,2},{“ b”,4},{“ b”,“ 5”}时,需要将其处理为{“ a”,3 },{“ b”,9}。
当然,结合方法是将相同类型的对象的计数相加。
怎么做?
您可以Collectors.toMap
用来将流收集到所需的流中Map
。
演示:
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class MyType {
String type;
int count;
public MyType(String type, int count) {
this.type = type;
this.count = count;
}
public String getType() {
return type;
}
public int getCount() {
return count;
}
}
public class Main {
public static void main(String[] args) {
List<MyType> list = List.of(new MyType("a", 1),
new MyType("a", 2),
new MyType("b", 4),
new MyType("b", 5));
Map<String, Integer> map = list.stream()
.collect(Collectors.toMap(MyType::getType, MyType::getCount, Integer::sum));
System.out.println(map);
}
}
输出:
{a=3, b=9}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句