Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a key to HashMap without the value?

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?

like image 581
LuxuryMode Avatar asked May 18 '11 13:05

LuxuryMode


2 Answers

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", "สวัสดี"]
like image 85
Matt Ball Avatar answered Oct 16 '22 19:10

Matt Ball


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.

like image 4
Richard H Avatar answered Oct 16 '22 19:10

Richard H