If you are using java-8 or later then
List<Drink> list = new ArrayList<>();
list.add(new Drink("coke", 30));
list.add(new Drink("fanta", 10));
list.add(new Drink("coke", 5));
list.add(new Drink("sprite", 1));
list.add(new Drink("coke", 10));
Map<String, Integer> map = list.stream()
.collect(Collectors.groupingBy(Drink::getName,
Collectors.summingInt(Drink::getAmount)));
System.out.println(map);
output
{sprite=1, coke=45, fanta=10}
Collection<Drink> c =
list.stream().collect(Collectors.groupingBy(Drink::getName,
Collectors.collectingAndThen(
Collectors.reducing((Drink a, Drink b) -> {
a.setAmount(a.getAmount() + b.getAmount());
return a;
}), Optional::get))).values();
2
solved Extracting objects from a list by quantity [closed]