0

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.

1
  • You should change the subject to say MultiMap, because that's what you apparently need. Associative array is simply a hash table, or a hash map. Commented Aug 24, 2016 at 17:51

5 Answers 5

3

Yes, it is possible in Java. Check apache's MultiMap.

Sign up to request clarification or add additional context in comments.

3 Comments

I think apache's multihashmap is deprecated.
@user1021904 No it was just moved to the map subpackage.
Perhaps you should link to 4.1 Javadoc.
3

I like the MultiMap answer above. But if you want to stick to the java.util collections, try a map of lists.

4 Comments

please help me how to do that?
MultiMap is just a nicer API wrapper around a Map with ArrayList keys anyway.
@user1021904 - show us your attempt at using a map of lists if you want help.
To respond to "how to do that" more details are required. Are duplicates required/not required? Do you just want to build the map? Do you need to remove or update keys, remove or update values in the map, and so on. It's not hard, but maybe using MultiMap is your best move here.
3

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.

Comments

2

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.

1 Comment

Kunda bora - you need to learn how to use Markdown to format your Answers properly. Read the Help page.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.