在HashMap中添加一个没有值的键?

17
有没有一种方法可以向HashMap添加键而不添加值?我知道这似乎很奇怪,但我有一个HashMap<String,Arraylist<Object>>,我想首先能够根据需要创建键,然后检查某个键是否存在,并且如果存在,放入适当的值,即ArrayList<Object>
这足够令人困惑了吗?
5个回答

29

由于您正在使用 Map<String, List<Object>>,因此您实际上是在寻找一个多重映射。 我强烈建议使用第三方库,例如Google Guava,有关详细信息,请参见Guava的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更新:我不再认为每个Map<K,SomeCollection<V>>都应该重写为Multimap。如今,借助于Map#computeIfAbsent(),很容易获得所需的内容而无需使用Guava。
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", "สวัสดี"]

4
我不确定你是否想这样做。您可以将null作为键的值进行存储,但如果这样做,当您执行.get("key")时,如何判断该键是否存在,或者如果它确实存在但其值为null?无论如何,请参见文档

3

您可以放置null值。这是由HashMap允许的。

您也可以最初使用一个Set,检查其中是否有该键,然后再填充地图。


4
或者直接使用Guava的Multimaps! - Matt Ball
嗨Bozho - 我发现这个问题,因为我正在尝试做类似的事情,你的答案真的很有帮助。您能否详细说明如何初始化一个集合,然后在向其中添加对象时将其转换为HashMap? - javapalava

3

是的,这很令人困惑 ;) 我不明白为什么你想存储没有值的键,而不是将空的ArrayList放入null中。

添加null可能会有问题,因为如果你调用

map.get("somekey");

如果你收到一个null,那么你就不知道这个键是不存在还是存在但映射到null...


1
如果你添加了 null,你可以使用 containsKey() 进行测试。 - sarumont
1
@sarumont - 当然可以,但你必须知道只有这种方法适用于map。如果一个map返回map.get("key") == nullmap.contains("key") == true,我会感到惊讶... - Andreas Dolk
它至少可以与java.util.HashMap一起使用。map.put(“foo”,null)对于map.containsKey(“foo”)返回true,对于map.get(“foo”)返回null。 - sarumont
1
@sarumont - 当然:确切地说,那种行为 会让我感到惊讶(在实际代码中)。 ;) - Andreas Dolk
哦,我现在明白你的意思了。 :) 我也会感到惊讶,但不会过度 - 不幸的是,我见过更糟糕的情况。 ;) - sarumont

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/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接