Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert Map <String, List<String>> using Java 8 streams

I need to invert a map which is <String, List<String>> to Map<String,String> using Java 8, with the assumption that the values are unique. For example,

Input map -

{"Fruit" -> ["apple","orange"], "Animal" -> ["Dog","Cat"]}

Output map

{"apple" -> "Fruit", "orange" -> "Fruit", "Dog"->"Animal", "Cat" -> "Animal"}
Map <String, String> outputMap = new HashMap<>();
for (Map.Entry<String, List<String>> entry : inputMap.entrySet()) {
    entry.getValue().forEach(value -> outputMap.put(value, entry.getKey()));
}   

Is this right? Can we achieve this using streams Java 8?

like image 766
Shiny Avatar asked Feb 21 '26 17:02

Shiny


1 Answers

Do like this :

public class InverterMap {
    public static void main(String[] args) {

        Map<String, List<String>> mp = new HashMap<String, List<String>>();
        mp.put("Fruit", Arrays.asList("Apple", "Orange"));
        mp.put("Animal", Arrays.asList("Dog", "Cat"));
        System.out.println(mp);  // It returned {Fruit=[Apple, Orange], Animal=[Dog, Cat]}

        Map<String, String> invertMap = mp.entrySet().stream().collect(HashMap::new,
            (m, v) -> v.getValue().forEach(k -> m.put(k, v.getKey())), Map::putAll);

        System.out.println(invertMap);// It returned {Apple=Fruit, Cat=Animal, Orange=Fruit, Dog=Animal}

    }

}

Read Stream.collect(Supplier supplier, BiConsumer, BiConsumer combiner) for more info.

like image 74
Vinay Hegde Avatar answered Feb 24 '26 16:02

Vinay Hegde