I have a class like this
ObjectA
id
type
where id is unique but the type can be duplicate so if I have a list of ObjectA like this
(id, type) = (1, "A") , (2, "B"), (3, "C"), (4, "A")
then I want Map<type, List<id>>
where
map is
< "A",[1,4],
"B",[2],
"C",[3] >
It is working with Java 7 but can't find a way to do it in Java 8. In Java 8 I can create key, value pair but not able to create a list if a type is same.
yourTypes.stream()
.collect(Collectors.groupingBy(
ObjectA::getType,
Collectors.mapping(
ObjectA::getId, Collectors.toList()
)))
A way to do it without streams:
Map<String, List<Integer>> map = new HashMap<>();
list.forEach(object ->
map.computeIfAbsent(object.getType(), k -> new ArrayList<>())
.add(object.getId()));
This uses Iterable.forEach
and Map.computeIfAbsent
to iterate the list
and group its elements (here named object
) by its type
attribute, creating a new ArrayList
if there was no entry for that type in the map yet. Then, the id
of the object is added to the list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With