我使用Java 8流和groupingBy方法为您的问题实施了两种解决方案。我希望这能帮到您。
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static class Ingredient {
private final String name;
private final int quantity;
public Ingredient(String name, int quantity) {
Objects.requireNonNull(name);
this.name = name;
this.quantity = quantity;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
@Override
public String toString() {
return "Ingredient{" +
"name='" + name + '\'' +
", quantity=" + quantity +
'}';
}
}
public static void main(String[] args) {
Ingredient[] ingredients = new Ingredient[]{
new Ingredient("banana", 1),
new Ingredient("cherry", 5),
new Ingredient("banana", 3),
new Ingredient("floor", 1)
};
// First solution: Group all quantities
Map<String, List<Integer>> collect = Arrays.stream(ingredients)
.collect(Collectors.groupingBy(Ingredient::getName,
Collectors.mapping(Ingredient::getQuantity, Collectors.toList())
));
System.out.println(collect);
// Second solution: Sum all quantities
Map<String, Integer> sum = Arrays.stream(ingredients)
.collect(
Collectors.groupingBy(Ingredient::getName,
Collectors.summingInt(Ingredient::getQuantity)
));
System.out.println(sum);
}
}
'map.put(duplicatePortion。getName(),新的IngredientPortion(duplicatePortion.getName(),alreadyStoredPortion.quantity + duplicatePortion.quantity)' –
[HashMap在同一个键下具有多个值的HashMap的可能重复](http://stackoverflow.com/questions/4956844/hashmap -with-multiple-values-under-the-same-key) – nhouser9
您尚未提供您现有的代码或显示地图的定义,特别是输入值的类型。它是'Double','BigDecimal'还是自定义类? –