Reputation: 97
I want add duplicate keys in map,output like the one below:
google:Android,google:Maps,apple:iPod,apple:iPhone,apple:iOS
Is it possible in java or json? please help me.
Upvotes: 0
Views: 1281
Reputation: 3332
Another good solution apart from Apache's library is to use Google's guava libraries. Guava implements a Multimap, and here's a blog post that explains how to use Guava's Multimaps
Upvotes: 0
Reputation: 25676
Even better than a map of lists is a map of sets, assuming you only want to allow duplicate keys and not duplicate associations. It could be done like this:
import java.util.*;
Map<K, Set<V>> yourMap = new HashMap<K, Set<V>>();
public void add(K key, V value) {
if (!yourMap.containsKey(key)) {
yourMap.put(key, new HashSet<V>());
}
yourMap.get(key).add(value);
}
Replace K
and V
with the actual key and value types.
Upvotes: 3
Reputation: 3889
Map in java can never has duplicate key, however you can put multiple values for a particular key:
Map<String, List<String>> map = new HashMap<String, List<String>>();
You can also use MultivaluedMap
.
Upvotes: 2
Reputation: 18143
I like the MultiMap answer above. But if you want to stick to the java.util collections, try a map of lists.
Upvotes: 3