class Ob {
private String type;
private List<String> attire;
// standard getter and setters
public Ob (String type){
this.type=type;
}
public Ob addAttrire(String att){
if(attire == null){
attire = new ArrayList<>();
}
attire.add(att);
return this;
}
}
我接收对象为
[{
"type" : "upper"
attires : [{"t1","t2"}]
},
{
"type" : "upper"
attires : ["t3","t4"]
},
{
"type" : "lower"
attires : ["l1","l2"]
}]
对象Ob
的名单,我必须为
[{
"type" : "upper"
attires : ["t1","t2","t3","t4"]
},{
"type" : "lower"
attires : ["l1","l2"]
}]
如何使用流来做到这一点。是否减少帮助? 一个可以使用的流是
List<Ob> coll = new ArrayList<>();
coll.add(new Ob("a").addAttrire("1").addAttrire("2").addAttrire("3"));
coll.add(new Ob("a").addAttrire("1").addAttrire("2").addAttrire("3"));
coll.add(new Ob("a").addAttrire("1").addAttrire("2").addAttrire("3"));
coll.add(new Ob("b").addAttrire("1").addAttrire("2").addAttrire("3"));
coll.add(new Ob("b").addAttrire("1").addAttrire("2").addAttrire("3"));
coll.add(new Ob("b").addAttrire("1").addAttrire("2").addAttrire("3"));
Collection<Ob> values = coll.stream()
.collect(toMap(Ob::getType, Function.identity(), (o1, o2) -> {
o1.getAttire().addAll(o2.getAttire());
return o1;
})).values();
更新与鲁的溶液的问题。没有要求删除重复项,但可以使用Ob中的set for set装完成。目前的解决方案完美无缺。
关于鲁本斯回答您的评论是合并函数“*什么在这样的情况下,性能的影响*推荐的方式”:我认为在运行时性能没有太大的区别。如果性能在这里成为一个问题,我认为最好用循环重写代码,这会给你更多的控制权。我认为鲁本斯解决方案具有优势,因为它更短,更简单。我认为我有一个优势,因为它不会修改原来的“Ob”,因此更具有功能风格。 – Lii