Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java group a map by value where value is a List

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

TQ in advance for any piece of advice.

>Solution :

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]}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading