【发布时间】:2018-05-06 16:19:30
【问题描述】:
我想在 Java 8 中将 NxN 数组映射到 Map。
这个想法是每个 [i][0] 元素都是一个键,每个 j>0 的 [i][j] 是映射中每个键的值列表。
感谢您的帮助。 :)
这是我的课:
public class GroupingDishes {
public static void main(String[] args) {
String[][] dishes = {
{"Salad", "Tomato", "Cucumber", "Salad", "Sauce"},
{"Pizza", "Tomato", "Sausage", "Sauce", "Dough"},
{"Quesadilla", "Chicken", "Cheese", "Sauce"},
{"Sandwich", "Salad", "Bread", "Tomato", "Cheese"}
};
Map<String, HashSet<String>> groupDishes = groupingDishes(dishes);
}
public static Map<String, HashSet<String>> groupingDishes(String[][] dishes) {
Map<String, HashSet<String>> mapFood = new HashMap<>();
for (int i = 0; i < dishes.length; i++) {
String food = dishes[i][0];
for (int j = 0; j < dishes[i].length; j++) {
if (mapFood.containsKey(food)) {
HashSet<String> existingIngredients = mapFood.get(dishes[i][0]);
existingIngredients.add(dishes[i][j]);
mapFood.put(food, existingIngredients);
} else {
HashSet<String> newIngredient = new HashSet<>();
mapFood.put(food, newIngredient);
}
}
}
return mapFood;
}
}
【问题讨论】:
标签: java arrays lambda java-8 hashmap