【发布时间】:2020-04-22 15:41:30
【问题描述】:
鉴于: 包含水果的地图
enum Food{
FRUITS, VEGGIES;
}
Map<String, Map<Food, List<String>>> fruitBasket= new HashMap<>();
fruitBasket.put("basket1", Collections.singletonMap(Food.FRUITS, Arrays.asList("apple","banana")));
fruitBasket.put("basket2", Collections.singletonMap(Food.FRUITS, Arrays.asList"orange", "kiwi")));
fruitBasket.put("basket3", Collections.singletonMap(Food.FRUITS, Arrays.asList("banana", "orange")));
fruitBasket:
[
basket1, [Food.FRUITS, {"apple", "banana"}],
basket2, [Food.FRUITS, {"orange", "kiwi"}],
basket3, [Food.FRUITS, {"banana", "orange"}]
]
同样是另一张包含 VEGGIES 的地图
Map<String, Map<Food, List<String>>> veggieBasket= new HashMap<>();
veggieBasket.put("basket1", Collections.singletonMap(Food.VEGGIES, Arrays.asList("Tomato","Onion")));
veggieBasket.put("basket2", Collections.singletonMap(Food.VEGGIES, Arrays.asList("Onion", "Potato")));
veggieBasket.put("basket3", Collections.singletonMap(Food.VEGGIES, Arrays.asList("Potato", "Tomato")));
veggieBasket:
[
basket1, [Food.VEGGIES, {"Tomato","Onion"}],
basket2, [Food.VEGGIES, {"Onion", "Potato"}],
basket3, [Food.VEGGIES, {"Potato", "Tomato"}]
]
我正在尝试组合篮子 fruitBasket 和 veggieBasket
Final output: should look something like below
groceryBasket
[
basket1, [Food.FRUITS, {"apple", "banana"}, Food.VEGGIES, {"Tomato","Onion"}],
basket2, [Food.FRUITS, {"orange", "kiwi"}, Food.VEGGIES, {"Onion", "Potato"}],
basket3, [Food.FRUITS, {"banana", "orange"}, Food.VEGGIES, {"Potato", "Tomato"}]
]
我的解决方案:
Solution 1:
Map<String, Map<Food, List<String>>> groceryBasket= new HashMap<>();
grocery basket = Stream.concat(fruitBasket.entrySet().stream(), veggieBasket.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (fruitList, veggieList ) ->
{
final List<String> groceryList = new ArrayList<>();
groceryList .addAll(fruitList);
groceryList .addAll(veggieList);
return groceryList;
}));
Solution 2:
Map<String, Map<Food, List<String>>> groceryBasket= new HashMap<>();
grocery basket = Stream.concat(fruitBasket.entrySet().stream(), veggieBasket.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (fruitList, veggieList ) ->
{
return Stream.of(fruitList, veggieList).flatMap(x -> x.stream()).collect(Collectors.toList());
}));
我尝试了解决方案 1 和解决方案 2,我想知道是否有更好/优化的方法来处理这个问题?
【问题讨论】:
标签: java collections java-8 java-stream