Reputation: 96
I have an object, "Item" with fields: int: id String: prices
The string prices contains one or more price values separated by comma.
Problem: Using stream operations I want a map of type Map<Integer,Set<Integer>>
from List<Item> items
where key of Map is id and Set has value of prices as Integer extracted from the String prices.
There will be repeated ids in the List and can have different price strings.
I have come up with an approach which produces the following result:
Map<Integer, Set<List<Integer>>> itemStoresMapIntermediate = items.stream()
.collect(Collectors.groupingBy(Item::getItemId,Collectors.mapping(Item::getStoresAsIntList, Collectors.toSet())));
getStoresAsIntList() returns List of price values from String prices in the object.
The above is certainly not what I want.
Upvotes: 2
Views: 95
Reputation: 121048
If I understood correctly...
Item item1 = new Item(1, "22,23,24");
Item item2 = new Item(2, "33,34,35");
Item item3 = new Item(1, "22,57,58");
Map<Integer, Set<Integer>> map = Stream.of(item1, item2, item3)
.collect(Collectors.toMap(
Item::getId,
i -> new HashSet<>(i.getStoresAsIntList()),
(left, right) -> {
left.addAll(right);
return left;
}, HashMap::new));
System.out.println(map); // {1=[22, 23, 24, 57, 58], 2=[33, 34, 35]}
Upvotes: 5