简体   繁体   English

从 map 检索密钥列表

[英]Retrieve List of keys from map

HashMap<String,String> map=new HashMap<>();
        map.put("name","x");
        map.put("value", "yes");
HashMap<String,String> map1=new HashMap<>();
        map1.put("name","y");
        map1.put("value", "yes");

I want how to get values for specific key i want the solution like(x,y)我想如何获取特定键的值我想要像(x,y)这样的解决方案

In order to get hashMap's keys set, you can call HashMap#keySet()为了得到 hashMap 的键集,你可以调用 HashMap#keySet()

In order to get HashMap's values set, you can call hashMap#values()为了获取 HashMap 的值集,您可以调用 hashMap#values()

Now, if you wanna get a value of a specific key, you can do it with HashMap#entrySet(), it returns a set of every key with relative value, then check egery one with an if-statement and you've done现在,如果您想获取特定键的值,可以使用 HashMap#entrySet() 来完成,它返回一组具有相对值的每个键,然后使用 if 语句检查 egery 一个,您就完成了

doc 文档

Map has the method "keySet()" for getting Set of keys, for getting List from Set you can use ArrayList's a constructor: Map具有用于获取键集的方法“keySet()”,为了从 Set 中获取 List,您可以使用 ArrayList 的构造函数:

List<String> result = new ArrayList<>(map.keySet());

for getting element from List:从列表中获取元素:

for(String name: result){
   if(name.equals("someName")){
   System.out.println(name);
  }
 }

Please note that if you are using String as key values, then you need to include code to eliminate duplicate string values from map.请注意,如果您使用字符串作为键值,则需要包含代码以消除 map 中的重复字符串值。 That is why having String as key is not a good Idea.这就是为什么将 String 作为键不是一个好主意的原因。 Otherwise, write specific Code to eliminate duplicate String values from hashmap by Iterating key values from Hashmap(KeySet).否则,编写特定代码,通过迭代 Hashmap(KeySet) 中的键值来消除 hashmap 中的重复字符串值。 Construct one more Hashmap and push values from both maps into another map.再构造一个 Hashmap 并将两个映射中的值推送到另一个 map。 Once again, Please be careful about duplicate x values in the third map(Just as stated above, write code for eliminating duplicate x values).再一次,请注意第三张地图中重复的 x 值(如上所述,编写用于消除重复 x 值的代码)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM