gpt4 book ai didi

java - 向 HashMap 添加集合

转载 作者:行者123 更新时间:2023-12-01 18:56:36 25 4
gpt4 key购买 nike

我需要帮助向 HashMap 添加一个集合:每次我向集合添加一个值时,它都会获取键的集合,并将新值添加到集合中,然后将集合放回原处。

显示方法应该只返回已经完成的 HashMap 。

package HashMap;

import java.util.HashMap;
import java.util.Set;

public class Thesaurus {
HashMap<String, Set<String>> words =new HashMap<String,Set<String>>();

public void add(String x,String y)
{
words.put(x,words.get(x).add(y));
}
public void display()
{
System.out.println(words);
}
public static void main(String[] args) {
Thesaurus tc = new Thesaurus();
tc.add("large", "big");
tc.add("large", "humoungus");
tc.add("large", "bulky");
tc.add("large", "broad");
tc.add("large", "heavy");
tc.add("smart", "astute");
tc.add("smart", "clever");
tc.add("smart", "clever");
tc.display();
}
}

最佳答案

public void add(String x,String y) {
Set<String> set = words.get(x);
if (set == null) {
words.put(x, set = new HashSet<String>());
}
set.add(y);
}

关于java - 向 HashMap 添加集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13753843/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com