Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of objects to map in java 8

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.

like image 524
user1298426 Avatar asked Feb 12 '18 13:02

user1298426


2 Answers

yourTypes.stream()
         .collect(Collectors.groupingBy(
               ObjectA::getType,
               Collectors.mapping(
                    ObjectA::getId, Collectors.toList()
)))
like image 52
Eugene Avatar answered Oct 03 '22 14:10

Eugene


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.

like image 45
fps Avatar answered Oct 03 '22 14:10

fps