3 回答

TA贡献1872条经验 获得超3个赞
您可以BinaryOperator<U> mergeFunction在 Collectors.toMap 中使用。
Collection<Wrapper> wrapperList = wrappers.stream()
.collect(Collectors.toMap(Wrapper::getId, x -> x),
(oldVal, newVal) -> {
oldVal.getElements().addAll(newVal.getElements());
return oldVal;
}))
.values();
在上面的代码中,我写mergeFunction了总是返回 oldVal(oldVal, newVal) -> oldVal但你可以改变你想要的方式。Lambda 函数x -> x也可以写成Function.identity().

TA贡献1874条经验 获得超12个赞
您可以使用Collectors.toMap()合并功能添加地图的值。
Map<Integer, Wrapper> collect =
list.stream()
.collect(Collectors.toMap(w -> w.id,
w -> w,
(w1, w2) -> {
w1.list.addAll(w2.list);
return w1;
})
);
在职的
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<Wrapper> list=new ArrayList();
ArrayList<Element> listForWrapper1= new ArrayList();
listForWrapper1.add(new Element("Content A"));
listForWrapper1.add(new Element("Content B"));
ArrayList<Element> listForWrapper2= new ArrayList();
listForWrapper2.add(new Element("Content C"));
listForWrapper2.add(new Element("Content D"));
ArrayList<Element> listForWrapper3= new ArrayList();
listForWrapper3.add(new Element("Content E"));
listForWrapper3.add(new Element("Content F"));
Wrapper wrapper1=new Wrapper(1,listForWrapper1);
Wrapper wrapper2=new Wrapper(2,listForWrapper2);
//Here this Wrapper has the same ID than wrapper2
Wrapper wrapper3=new Wrapper(2,listForWrapper3);
//Adding Elements to List
list.add(wrapper1);
list.add(wrapper2);
list.add(wrapper3);
Map<Integer, Wrapper> collect =
list.stream()
.collect(Collectors.toMap(w -> w.id,
w -> w,
(w1, w2) -> {
w1.list.addAll(w2.list);
return w1;
})
);
System.out.println( collect.values() );
}
}
class Wrapper {
Integer id ;
List<Element> list;
public Wrapper(Integer id, List<Element> list) {
this.id = id;
this.list = list;
}
@Override
public String toString() {
return id + ":" + list;
}
}
class Element {
String content ;
public Element(String content) {
this.content = content;
}
@Override
public String toString() {
return content;
}
}
输出
[1:[Content A, Content B], 2:[Content C, Content D, Content E, Content F]]

TA贡献1825条经验 获得超6个赞
你可以试试这个:
Map<Integer, Wrapper> map = list.stream().collect(Collectors.toMap(wrapper -> wrapper.id /*Use the ids as the keys*/, wrapper -> wrapper /*Return the same wrapper as the value*/, (w1, w2) -> {
w1.list.addAll(w2.list); // If a wrapper with the same id is found, then merge the list of wrapper 2 to the list of wrapper 1 and return wrapper 1.
return w1;
}));
list = new ArrayList<>(map.values()); // Create new ArrayList with the values of the map.
System.out.println(list); // [cci.Test$Wrapper@4eec7777, cci.Test$Wrapper@3b07d329]
添加回答
举报