17

Is there a way to add a key to a HashMap without also adding a value? I know it seems strange, but I have a HashMap<String, ArrayList<Object>> amd I want to first be able to create keys as needed and then check if a certain key exists and, if so, put the appropriate value, namely the ArrayList<Object>

Was that confusing enough?

0

5 Answers 5

29

Since you're using a Map<String, List<Object>>, you're really looking for a multimap. I highly recommend using a third-party library such as Google Guava for this - see Guava's Multimaps.

Multimap<String, Object> myMultimap = ArrayListMultimap.create();

// fill it
myMultimap.put("hello", "hola");
myMultimap.put("hello", "buongiorno");
myMultimap.put("hello", "สวัสดี");

// retrieve
List<String> greetings = myMultimap.get("hello");
                      // ["hola", "buongiorno", "สวัสดี"]

Java 8 update: I'm no longer convinced that every Map<K, SomeCollection<V>> should be rewritten as a multimap. These days it's quite easy to get what you need without Guava, thanks to Map#computeIfAbsent().

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

// fill it
myMap.computeIfAbsent("hello", ignored -> new ArrayList<>())
  .addAll(Arrays.asList("hola", "buongiorno", "สวัสดี");

// retrieve
List<String> greetings = myMap.get("hello");
                      // ["hola", "buongiorno", "สวัสดี"]
0
4

I'm not sure you want to do this. You can store null as a value for a key, but if you do how will be able to tell, when you do a .get("key") whether the key exists or if it does exist but with a null value? Anyway, see the docs.

0
3

You can put null values. It is allowed by HashMap

You can also use a Set initially, and check it for the key, and then fill the map.

2
  • 4
    ...or just use Guava's Multimaps!
    – Matt Ball
    May 18, 2011 at 14:05
  • Hi Bozho - I found this question because I'm trying to do something similar, and your answer is really helpful. Would you be able to elaborate on how you would go about initialising a set and then converting it to a HashMap when you add objects to it?
    – javapalava
    Mar 8, 2015 at 11:23
3

Yes, it was confusing enough ;) I don't get why you want to store keys without values instead just putting empty arraylists instead of null.

Adding null may be a problem, because if you call

map.get("somekey");

and receive a null, then you do not know, if the key is not found or if it is present but maps to null...

5
  • 1
    If you add null, you can test with containsKey().
    – sarumont
    May 18, 2011 at 16:39
  • 1
    @sarumont - sure, but you have to know that only this method works for the map. I'd be surprised if a map returns map.get("key") == null and map.contains("key") == true... May 18, 2011 at 16:58
  • it works with java.util.HashMap, at least. map.put( "foo", null ) yields true for map.containsKey( "foo" ) and null for map.get( "foo" )
    – sarumont
    May 18, 2011 at 17:42
  • 1
    @sarumont - sure: and exactly that behaviour would surprise me (in real code) ;) May 18, 2011 at 19:26
  • Oh, I see what you meant now. :) I would also be surprised, but not overly so - I've unfortunately seen worse. ;)
    – sarumont
    May 18, 2011 at 20:15
0
//This program should answer your questions
import java.util.*;
public class attemptAddingtoHashMap { //Start of program

//MAIN METHOD #################################################

public static void main(String args[]) {  //main begins

Map<String, ArrayList<Object>> hmTrial = new HashMap<String, ArrayList<Object>>(); 

ArrayList alTrial = new ArrayList();//No values now

if (hmTrial.containsKey("first")) {
hmTrial.put("first", alTrial); }

else {hmTrial.put("first",alTrial);}
//in either case, alTrial, an ArrayList was mapped to the string "first"
//if you choose to, you can also add objects to alTrial later
System.out.println("hmTrial is " + hmTrial); //empty now
alTrial.add("h");
alTrial.add("e");
alTrial.add("l");
alTrial.add("l");
alTrial.add("o");
System.out.println("hmTrial is " + hmTrial);//populated now

   } //end of main
//#############################################################################################################

} //end of class

//Note - removing objects from alTrial will remove the from the hashmap
//You can copy, paste and run this code on https://ide.geeksforgeeks.org/

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.