This might work for you:
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class Foo {
String name;
Integer noOfBalls;
public Foo(String name, Integer noOfBalls) {
this.name = name;
this.noOfBalls = noOfBalls;
}
public String getName() {
return name;
}
public Integer getNoOfBalls() {
return noOfBalls;
}
@Override
public String toString() {
return "Foo{" +
"name='" + name + ''' +
", noOfBalls=" + noOfBalls +
'}';
}
}
public class Test {
public static void main(String[] args){
ArrayList<Foo> arrayList = new ArrayList<>();
arrayList.add(new Foo("John",10));
arrayList.add(new Foo("Babu",1));
arrayList.add(new Foo("Alex",5));
arrayList.add(new Foo("Babu",5));
arrayList.add(new Foo("John",10));
ArrayList<Foo> arrayListTemp = arrayList.stream()
.collect(Collectors.collectingAndThen(Collectors.toMap(Foo::getName, Function.identity(), (left, right) -> {
left.noOfBalls= left.noOfBalls + right.noOfBalls;
return left;
}), m -> new ArrayList<>(m.values())));
arrayListTemp.sort(Comparator.comparingInt(Foo::getNoOfBalls));
arrayListTemp.forEach(System.out::println);
}
}
Here I am converting list to map(key as name
and value as Foo object) and if the name
already exists then merging Foo
object by adding noOfBalls
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…