Дано: Карта, содержащая ФРУКТЫ
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"}]
]
MySolution:
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, я пытался выяснить, есть ли лучший / оптимизированный способ справиться с этим?