Last time I was looking for a way to convert a Map into a Map of List. In otherwise direction, I mean backward from value up to key. Below you might find an solution for that problem using of course main Java 8 components like stream, filter, grouping and mapping.
Map<String, String> input = new HashMap<>(); input.put("SHARK", null); input.put("DOG", "HOME"); input.put("CAT", "HOME"); input.put("TURTLE", "HOME"); input.put("RABBIT", "HOME"); input.put("LION", "NOT_HOME"); input.put("HIPPO", "NOT_HOME"); input.put("TIGER", "NOT_HOME"); input.put("ZEBRA", "NOT_HOME"); Map<String, List<String>> result = input.entrySet().stream() .filter(i -> i.getValue() != null) .collect(Collectors.groupingBy(i -> i.getValue(), Collectors.mapping(i -> i.getKey(), Collectors.toList())));
Results
Key : HOME with List of DOG, CAT, TURTLE and RABBIT
Key : NOT_HOME with List of LION, HIPPO, TIGER, ZEBRA
Convert Map into Map of List - Java 8
2017-07-09T15:07:00+01:00
GarciaPL
Java|Java 8|