0

I have stuck up with an issue of retrieving data using java. Can any one guide me how to find the solution of it.

       Map<String,String> map = new HashMap<String,String>();
        map.put("8004","Lead");
        map.put("8004","Opportunity");
        map.put("8004","Quote");
        map.put("8004","Contract");

        map.put("8005","CreatContract" );
        map.put("8005","ManageContract" );
        map.put("8005","SelectContract" );
        //System.out.println(map);

        Iterator<Entry<String, String>> it = map.entrySet().iterator();
        while(it.hasNext()){
             Map.Entry pair = (Map.Entry)it.next();
             //boolean blnExists = map.containsValue(pair.getValue());
             System.out.println(pair.getKey() + " = " + pair.getValue());
        }

Output:

8004 = Contract
8005 = SelectContract

Expected Ouput:

8004 = lead,opportunity,Quote
8005 = CreateContracr,ManageContract
4
  • Map<String, Set<String>>. Use Map.computeIfAbsent to create the initial Set. Commented Jul 7, 2016 at 7:47
  • Where does this data really come from? Can you share a more "real" example? Commented Jul 7, 2016 at 7:49
  • Possible duplicate of How to have multimap functionality in Java? Commented Jul 7, 2016 at 7:50
  • Using a Map<?,?> and passing the same key twice while putting data into the map, will always overwrite the value not double it. Commented Jul 7, 2016 at 7:51

6 Answers 6

2

When you call put on a HashMap when there is already an entry in the map for the given key, then the value that you pass will replace whatever was in the map for that key. So if you do this:

map.put("8004","Lead");
map.put("8004","Opportunity");

then the second put will overwrite the value of the first put. You'll have to check yourself if the map already contains a value, and append your new value if it does. For example, write a utility method:

public void putAppend(Map<String, String> map, String key, String value) {
    if (map.containsKey(key)) {
        map.put(key, map.get(key) + "," + value);
    } else {
        map.put(key, value);
    }
}

Then use it:

putAppend(map, "8004", "Lead");
putAppend(map, "8004", "Opportunity");

If you want the value to actually be a List and not a String, then change the map appropriately:

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

And make the putAppend method look like this:

public void putAppend(Map<String, List<String>> map, String key, String value) {
    if (!map.containsKey(key)) {
        map.put(key, new ArrayList<>());
    }

    map.put(key, map.get(key).add(value));
}

If you are using Java 8, you can use computeIfAbsent and a lambda expression:

public void putAppend(Map<String, List<String>> map, String key, String value) {
    map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
}

You could also use a library such as Google Guava, which has a Multimap, which is a Map that can hold multiple values for one key.

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

Comments

1

If you actually want a Map<String, String> where the value is a comma separated list of values then you can use Map.merge rather than Map.put:

map.merge("8004", "Lead", (l, r) -> l + "," + r);

If you want a more sensible data structure, then using a Map<String, Set<String>> would be better as you store the individual items, rather than having to split then later, in that case, use Map.computeIfAbsent:

map.computeIfAbsent("8004", k -> new HashSet<>()).add("Lead");

Comments

1
public HashMap<String, String> extendKeyValuePairForHashMap(HashMap<String, String> hashMap, String key, String value) {
    if (hashMap.containsKey(key)) {
        hashMap.put(key, hashMap.get(key) + ", " + value);
    } else {
        hashMap.put(key, value);
    }
    return hashMap;
}

HashMap.put() will replace any current key value pair with the new key value pair specified, if the keys match. However you want to extend it, so you need to check if the key exists, if it does, then you need to get said current value, add your new one and put that into the HashMap

1 Comment

@BoristheSpider Still on Java 7 here I'm afraid
0

A HashMap stores your result as a pair Key - Value. Everytime your store a new pair, if the key already exists, it is replaced. That is why you only have the last element corresponding to the key.

What you want is:

Map<String, List<String>> map = new HashMap<String, ArrayList<String>>();

// Create your list
List<String> list8004 = new ArrayList<String>();
list8004.add("Lead");
list8004.add("Opportunity");
list8004.add("Quote");
list8004.add("Contract");

map.put("8004", list8004);

// Then do the same for 8005
List<String> list8005 = new ArrayList<String>();
list8005.add("CreatContract");
list8005.add("ManageContract");
list8005.add("SelectContract");

map.put("8005", list8004);

// Finally access
Iterator<Entry<String, List<String>>> it = map.entrySet().iterator();
while(it.hasNext()){
     Map.Entry pair = (Map.Entry)it.next();
     System.out.print(pair.getKey() + " = ");
     for (String s : pair.getValue()){
         System.out.print(s + " ");
     }
     System.out.println();    
 }

1 Comment

s/new HashMap<String, ArrayList<String>>()/new HashMap<>()/g.
0

Use MultiMap from guava instead of Map, in it you can store multiple values in a single key (I've also used foreach loop instead of iterator which you had):

    Multimap<String, String> map = ArrayListMultimap.create();
    map.put("8004","Lead");
    map.put("8004","Opportunity");
    map.put("8004","Quote");
    map.put("8004","Contract");
    map.put("8005","CreatContract" );
    map.put("8005","ManageContract" );
    map.put("8005","SelectContract" );
    //System.out.println(map);

    for (Map.Entry<String, String> pair : map.entries()) {
         System.out.println(pair.getKey() + " = " + pair.getValue());
    }

Comments

0

You need to create a Map<String, List<String>> map = new HashMap<>();. Plaese look below snippet : import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry;

public class Test {

    private static Map<String, List<String>> map = new HashMap<>();

    public static void main(String args[]){
     addDataToMap("8004","Lead");
     addDataToMap("8004","Opportunity");
     addDataToMap("8004","Quote");
     addDataToMap("8004","Contract");

     addDataToMap("8005","CreatContract" );
     addDataToMap("8005","ManageContract" );
     addDataToMap("8005","SelectContract" );

     Iterator<Entry<String, List<String>>> it = map.entrySet().iterator();
     while(it.hasNext()){
          Map.Entry pair = (Map.Entry)it.next();
          System.out.println(pair.getKey() + " = " + pair.getValue());
     }
    }

    public static void addDataToMap(final String key, final String value){
        if(map.containsKey(key)){
            List<String> values = map.get(key);
            values.add(value);
        }else{
            List<String> values = new ArrayList<>();
            values.add(value);
            map.put(key, values);
        }

    }
}

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.