Java 使用hashset作为值编辑hashmap

Java 使用hashset作为值编辑hashmap,java,Java,我有以下代码: HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>(); public static void indexDB(String base) { for(Person i: listB) { if(name.equals(base)) { } } 我希望它打印每次调用

我有以下代码:

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(name.equals(base))
        {

        }
}
我希望它打印每次调用的密钥的哈希集中包含的人员

谢谢你做这个

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
HashSet<Person> h = new HashSet<String>();
    for(Person i: listB)
    {
        //I assume it is i.name here
        if(i.name.equals(base))
        {
            h.add(i);
        }
    }
     index.put(base,h);
}

使用
putIfAbsent
插入空哈希集占位符

然后将新人员添加到现有集合:

HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(name.equals(base))
        {
            index.putIfAbsent(base, new HashSet<>());
            index.get(base).add(i)
        }
}
HashMap index=newhashmap();
公共静态void indexDB(字符串基)
{
对于(个人i:listB)
{
if(名称等于(基数))
{
putIfAbsent(base,new HashSet());
index.get(base).add(i)
}
}

注意:为了正确地将person添加到set,您必须为
person
类实现
equals()/hashCode()
,因为
set
使用equals()来确定唯一性

而不是在每次迭代中创建HashSet对象,只在名称匹配时创建它,如下面的代码中所示-

public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(index.containsKey(base)){
            HashSet<Person> existingHS = index.get(base);
            existingHS.add(i);
            index.put(base,existingHS);
        }else{
            HashSet<Person> hs = new HashSet<Person>();
            hs.add(i);
            index.put(base,hs);
        }
}
publicstaticvoidindexdb(字符串基)
{
对于(个人i:listB)
{
if(索引containsKey(基本)){
HashSet existingHS=index.get(base);
增加(i)项;
指数看跌期权(基准,现有的);
}否则{
HashSet hs=新的HashSet();
hs.添加(i);
指数.卖出价(基数,hs);
}
}

在h.add()中,您应该放置person对象,而不是类名本身:)@dericko yeah.对不起^ ^ ^这里putIfAbsent的用途是什么?put()也可以在这里工作如果您使用put,下一次迭代将用现有键的空集替换现有集。
putIfAbsent
等于
if(map.get(key)==null){map.put(键,值);}
如果您这样做,集合总是包含最多元素。这是错误的
HashMap<String, HashSet<Person>> index = new HashMap<String, HashSet<Person>>();
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(name.equals(base))
        {
            index.putIfAbsent(base, new HashSet<>());
            index.get(base).add(i)
        }
}
public static void indexDB(String base)
{
    for(Person i: listB)
    {
        if(index.containsKey(base)){
            HashSet<Person> existingHS = index.get(base);
            existingHS.add(i);
            index.put(base,existingHS);
        }else{
            HashSet<Person> hs = new HashSet<Person>();
            hs.add(i);
            index.put(base,hs);
        }
}