【问题标题】:Printing unique strings in HashMap在 HashMap 中打印唯一的字符串
【发布时间】:2022-01-11 09:14:08
【问题描述】:

我目前正在编写此代码,它假设输出某人的姓名,而列表中没有写他/她的姓名。 我只是想问一下如何使用 Map 进行这样的输出

输出: {安德鲁}

解释:Jay 写了 Susan,Susan 写了 Jay,Andrew 写了 Anna,Anna 写了 Jay 但没有人写 Andrew。

谢谢!

public class Main {

        public static void main(String[] args) {

                Main func = new Main();

                System.out.println(func.test("Jay:Susan,Susan:Jay,Andrew:Anna,Anna:Jay"));
        }
        public PriorityQueue test(String c) {
                Map < String, String > hmap = new HashMap < > ();
                PriorityQueue a = new PriorityQueue();

                String b = c.replaceAll("[,]", "-");
                System.out.println(b);
                String[] d = b.split("-");

                for (int i = 0; i < d.length; i++) {

                        String names = d[i];
                        String[] temp;
                        String splitter = ":";

                        temp = names.split(splitter);
                        String aName = temp[0];
                        String cName = temp[1];

                        hmap.put(aName, cName);

                }

                System.out.println(hmap);

                return a;
        }

}

【问题讨论】:

    标签: java hashmap


    【解决方案1】:

    在返回你的priorityQueue之前添加这个sn-p:

     Set<String> keys= new HashSet<>( hmap.values());
            for(Map.Entry<String, String> map: hmap.entrySet())
            {
                String key=map.getKey();
                if(!keys.contains(key))
                {
                    System.out.println(key);
                    a.add(key);
                }
            }
    

    我只是检查应该存在的集合中缺少哪个值。

    【讨论】:

    • 谢谢你!我之前尝试过使用类似的东西,但我没有意识到我将值与键混合在一起。
    • np。有时它可能发生在任何人身上
    【解决方案2】:

    使用集合的功能的另一种方法是在返回之前添加以下内容:

    //Extract all the voters into a new hashset, this will be modified
    Set<String> missing = new HashSet<>( hmap.keySet());
    //Use Collections.removeAll() to remove all the values from the keyset
    missing.removeAll(hmap.values());
    //Add the results to your queue
    a.addAll(missing);
    

    看看: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeAll-java.util.Collection-

    【讨论】:

      猜你喜欢
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-16
      • 2021-02-24
      相关资源
      最近更新 更多