【问题标题】:Compare the ArrayList values and HashMap values比较 ArrayList 值和 HashMap 值
【发布时间】:2017-06-25 05:35:30
【问题描述】:

我有一个关于 ArrayList 值与 HashMap 值比较的小查询,如果它们相等则提取键值。我正在读取两个文件并将它们分别存储在 ArrayList 和 HashMap 中。我必须比较这些值并从 HashMap 中提取键。

例如:

ArrayList<String> list=new ArrayList<String>();
list.add("A");
list.add("B");  
list.add("C");  
list.add("D");  
Iterator itr=list.iterator();  
while(itr.hasNext()){  
    System.out.println(itr.next());  
}

HashMap<String,String> hm=new HashMap<String,String>();  
hm.put("Key A","A");  
hm.put("Key B","B");  
hm.put("Key C","C");  
hm.put("Key D","D");  
for(Map.Entry m : hm.entrySet()){  
    System.out.println(m.getKey() + " " + m.getValue());  
}

我必须比较 ArrayList 和 HashMap,如果它们都包含值“A”,则应该返回 Key A。

【问题讨论】:

  • 首先查看如何找到列表包含项,然后检查如何获取哈希图的并查看是否它们也包含该项目,如果两个答案都返回为“true”,那么您可以迭代哈希图的条目,以查找值是所请求项目的键。祝你好运!
  • 我强烈建议您忽略答案并尝试自己实现它。诚然,这需要更多时间——但这正是你学习的方式。下次会容易得多!

标签: java dictionary arraylist hashmap


【解决方案1】:

只需遍历 HashMap 并查看某个值是否与来自 ArrayList 的值匹配

    HashMap<String,String> hm=new HashMap<String,String>();
    hm.put("Key A","A");
    hm.put("Key B","B");
    hm.put("Key C","C");
    hm.put("Key D","D");
    for(Map.Entry m : hm.entrySet()){
        if (list.contains(m.getValue()))
            System.out.println("Bingo: " + m.getKey());
    }

【讨论】:

  • 纯代码答案不适用于 Stack Overflow。请为您的代码添加解释。
【解决方案2】:

作为 bc004346 答案的替代方案,您还可以使用 Streams 以函数式风格解决这个难题:

List<String> result = hm.entrySet().stream()
    .filter(entry -> list.contains(entry.getValue()))
    .map(entry -> entry.getKey())
    .collect(Collectors.toList());

【讨论】:

    猜你喜欢
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-30
    • 1970-01-01
    相关资源
    最近更新 更多