Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert Map with list value Map<Key, List<Value>> to Map <Value, Key> in Java 8

I have a map kind of grouping values by key Map<String, List<Integer>>, i want to revert in order to map each value to the corresponding key

Example: I want to transform the code below

Map<String, List<Integer>> mapOfIntList = new HashMap<String, List<Integer>>();

mapOfIntList.put("UNIT", Arrays.asList(1, 2, 3, 8, 7, 0, 8, 6));
mapOfIntList.put("TEN", Arrays.asList(24, 90, 63, 87));
mapOfIntList.put("HUNDRED", Arrays.asList(645, 457, 306, 762));
mapOfIntList.put("THOUSAND", Arrays.asList(1234, 3456, 5340, 9876));

to another Map(Integer, String) where i can find : (1, "UNIT"), (2, "UNIT")...(24, "TEN"), (90, "TEN")...(645, "HUNDRED")...(3456, "THOUSAND")...

like image 419
Shessuky Avatar asked Jan 09 '19 15:01

Shessuky


People also ask

How do I reverse a Map in Java 8?

Method 1: ( Using reverse() method) This method is used to reverse the elements or mappings order in the LinkedHashMap. Parameters: myList is the List provided to the Collections. reverse(myList) method. Returns: It does not return anything but modifies the list internally.

How do I get the value of a Map for a specific key?

util. HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

Can we get key from value in HashMap?

Example: Get key for a given value in HashMap Here, the entrySet() method returns a set view of all the entries. Inside the if statement we check if the value from the entry is the same as the given value. And, for matching value, we get the corresponding key.

What is Map <> Java?

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction.


1 Answers

You can use

Map<Integer, String> mapNumberToType = mapOfIntList.entrySet().stream()
    .collect(HashMap::new, (m,e)->e.getValue().forEach(v->m.put(v,e.getKey())), Map::putAll);

You may recognize the similarity to the forEach based code of this answer within the second function passed to collect (the accumulator) function. For a sequential execution, they do basically the same, but this Stream solution supports parallel processing. That’s why it needs the other two functions, to support creating local containers and to merge them.

See also the Mutable reduction section of the documentation.

like image 183
Holger Avatar answered Oct 15 '22 12:10

Holger