I have a HashMap<String, List<Appliance>> where the field name::String from the object Appliance is used as a key, and each value in the HashMap is a list of Appliance objects. Each list, is sorted in ascending order, based on the field "price::BigDecimal", of the Appliance object. I would like to create an ArrayList<Appliance>, using the Stream API, and prexisted HashMap by extracting, first the first elements of each list in the HashMap, then the second ones, etc.
So if the HashMap has these contents:
["Fridge", [<"Fridge", 100>, <"Fridge", 200>, <"Fridge", 300>],
"Oven", [<"Oven", 150>, <"Oven", 250>, <"Oven", 350>],
"DishWasher", [<"DishWasher", 220>, <"DishWasher", 320>, <"DishWasher", 420>]]
I would like the final list to be as below:
[<"Fridge", 100>,
<"Oven", 150>,
<"DishWasher", 220>,
<"Fridge", 200>,
<"Oven", 250>,
<"DishWasher", 320>,
<"Fridge", 300>,
<"Oven", 350>,
<"DishWasher", 420>]
Is it possible to do that in a functional way using Java's 8 Stream API?
This is my code. I would like to achieve the same result in a declarative way.
while(!appliancesMap.isEmpty()) {
for (Map.Entry<String, List<Appliance>> entry :
appliancesMap.entrySet()) {
String key = entry.getKey();
List<Appliance> value = entry.getValue();
finalList.add(value.get(0));
value.remove(0);
if (value.size() == 0) {
appliancesMap.entrySet()
.removeIf(predicate -> predicate.getKey().equals(key));
} else {
appliancesMap.replace(key, value);
}
}
}
Steps:
IntStreamto iterate with the values from 0 to maximum size obtained in step#1i) of theIntStreamas the index to get the element from the list e.g. ifi = 0, get the element at index,0from each list inside the map and add toresultlistDemo
Output:
[Update]
Given below is the idiomatic code (Thanks to Holger) for the solution: