Home > database >  Java group a map by value where value is a List
Java group a map by value where value is a List

Time:11-10

I have a

Map<String,List<User>>map = new HashMap<>();
map.put("projectA",Arrays.asList(new User(1,"Bob"),new User(2,"John"),new User(3,"Mo")));
map.put("projectB",Arrays.asList(new User(2,"John"),new User(3,"Mo")));
map.put("projectC",Arrays.asList(new User(3,"Mo")));

Can use String instead of User.

String is a project Name but the same users can relate to different projects.

I would like to get sth like Map<User, List<String>> where the key will represent a distinct user and a value as a list of projects' names to which he/she relates.

Bob  = [projectA]
John = [projectA, projectB]
Mo   = [projectA, projectB, projectC]

TQ in advance for any piece of advice.

CodePudding user response:

Just loop over the map's entries and the List inside of them:

public static void main(String[] args) {
  Map<String, List<User>> map = new HashMap<>();
  map.put("projectA", Arrays.asList(new User(1,"Bob"),new User(2,"John"),new User(3,"Mo")));
  map.put("projectB",Arrays.asList(new User(2,"John"),new User(3,"Mo")));
  map.put("projectC",Arrays.asList(new User(3,"Mo")));

  Map<User, List<String>> result = new HashMap<>();
  for(Map.Entry<String, List<User>> e:map.entrySet()) {
    for(User u:e.getValue()) {
      result.putIfAbsent(u, new ArrayList<>());
      result.get(u).add(e.getKey());
    }
  }
  System.out.println(result);
}
public static record User(int id, String name) {}

prints

{User[id=1, name=Bob]=[projectA], User[id=2, name=John]=[projectB, projectA], User[id=3, name=Mo]=[projectB, projectA, projectC]}
  • Related