Map implementation with duplicate keys
You are searching for a multimap, and indeed both commons-collections and Guava have several implementations for that. Multimaps allow for multiple keys by maintaining a collection of values per key, i.e. you can put a single object into the map, but you retrieve a collection.
If you can use Java 5, I would prefer Guava's Multimap
as it is generics-aware.
Multimap implementation with duplicate keys
You can use groupingBy
which is the ideal case for you I think
Map<String, List<String>> res =
dataTypes.stream().collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toList())));
Mapping duplicate values from Map against the keys in which they are found
What you're trying to do is to invert the map (values become keys and keys get grouped by old values). There should be libraries that do that, but a sample solution with streams:
result = map.entrySet()
.stream()
.filter(e -> Collections.frequency(map.values(), e.getValue()) > 1)
.collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
How can i have a HashMap in Java with duplicate keys?
you need MultiMap
,
take a look at Google Guava Multimap
java map with duplicate keys
$ cat YourMap.java
public class YourMap extends HashMap<String, List<Integer>> {
public void put(String key, Integer number) {
List<Integer> current = get(key);
if (current == null) {
current = new ArrayList<Integer>();
super.put(key, current);
}
current.add(number);
}
public static void main(String args[]) {
YourMap m = new YourMap();
m.put("a", 1);
m.put("a", 2);
m.put("b", 3);
for(Map.Entry e : m.entrySet()) {
System.out.println(e.getKey() + " -> " + e.getValue());
}
}
}
$ java map
b -> [3]
a -> [1, 2]
Related Topics
Why Are Local Variables Not Initialized in Java
How to Add Custom Method to Spring Data JPA
Why Can Outer Java Classes Access Inner Class Private Members
Java: How to Start a Standalone Application from the Current One When Both Are in the Same Package
Sorting a Collection of Objects
How to Read a Specific Line Using the Specific Line Number from a File in Java
How to Ensure Order of Processing in Java8 Streams
Spring Boot and Multiple External Configuration Files
Java: Insert Multiple Rows into MySQL with Preparedstatement
Get Selected Rows in Jtable Using Abstracttablemodel
Ignoring New Fields on JSON Objects Using Jackson