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.
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.
Yes, it is possible in Java. Check apache's MultiMap.
map subpackage.I like the MultiMap answer above. But if you want to stick to the java.util collections, try a map of lists.
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.
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.
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