Question: There are fields with the same value in a certain list collection, how to find the sum of the values of other fields of the same field?
List:
**实体**
public class A{
private Long total;
private List<Way> ways;
}
**部分代码**
List<A> a = new ArrayList<>();
/**
{"total":"10",
"ways":[{"id":"1"}]
},
{"total":"5",
"ways":[{"id":"1"}]
},
{"total":"3",
"ways":[{"id":"2"}]
}
**/
//现在想把ways相同的合并成一个新的way,并且total相加即前两个10+5
List<a> afterA = a.stream.collect(Collectors.toMap(A::getWay,e->e,(o1,o2)->{
o1.setTotal(o1.getTotal()+o2.getTotal());
return o1;
})).valus().stream().collect(Collectors.toList());
expected outcome:
{
"total":"15",
"ways":[{
"id":"1"}]
},
{
"total":"3",
"ways":[{
"id":"2"}]
}
List(String) to List(Long) and other references: List collection type conversion