我正在尝试以<K, List<V>>格式创建字典。

private static Map<String, Collection<String>> dict = new HashMap<String, Collection<String>>();


使用new HashMap<>();new HashMap<String, ArrayList<String>>();引发不兼容的数据类型错误

我需要一本类似于以下字典的字典。

a: apple, ajar, axe, azure
b: ball, bat, box
d: dam, door, dish, drown, deer, dare
u: urn, umbrella
y: yolk


为此,我编写下面的代码。 put()返回不兼容的参数编译错误。在此示例中,使用put()的正确方法是什么?

dict.put("a", "apple");
dict.put("a", "ajar");
.
.
.
dict.put("u", "umbrella");
dict.put("y", "yolk");

最佳答案

您需要将List放置为地图的值,例如:

List<String> listA = Arrays.asList("apple", "ajar", "axe", "azure");
dict.put("a", listA);


另外,您可以使用guava Multimap,它允许将多个值映射到给定键。

09-10 05:56
查看更多