我有一个Java中的Hashmap,如下所示:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
然后我这样填写:
team1.put("United", 5);
我怎样才能获得钥匙?像:team1.getKey()
返回“联合国”。
HashMap
包含多个键。您可以使用keySet()
获取所有键的集合。
team1.put("foo", 1);
team1.put("bar", 2);
将存储1
与关键"foo"
和2
与关键"bar"
。迭代所有键:
for ( String key : team1.keySet() ) {
System.out.println( key );
}
将打印"foo"
和"bar"
。
public class MyHashMapKeys {
public static void main(String a[]){
HashMap<String, String> hm = new HashMap<String, String>();
//add key-value pair to hashmap
hm.put("first", "FIRST INSERTED");
hm.put("second", "SECOND INSERTED");
hm.put("third","THIRD INSERTED");
System.out.println(hm);
Set<String> keys = hm.keySet();
for(String key: keys){
System.out.println(key);
}
}
}
我要做的事情非常简单,但浪费内存是用键映射值,并执行oposite映射键的值为:
private Map<Object, Object> team1 = new HashMap<Object, Object>();
重要的是你使用<Object, Object>
所以你可以像这样映射keys:Value
和Value:Keys
team1.put("United", 5);
team1.put(5, "United");
所以如果你使用team1.get("United") = 5
和team1.get(5) = "United"
但是如果你在对中的一个对象上使用某种特定的方法,那么如果你制作另一个地图我会更好:
private Map<String, Integer> team1 = new HashMap<String, Integer>();
private Map<Integer, String> team1Keys = new HashMap<Integer, String>();
然后
team1.put("United", 5);
team1Keys.put(5, "United");
记住,保持简单;)
获得Key及其价值
e.g
private Map<String, Integer> team1 = new HashMap<String, Integer>();
team1.put("United", 5);
team1.put("Barcelona", 6);
for (String key:team1.keySet()){
System.out.println("Key:" + key +" Value:" + team1.get(key)+" Count:"+Collections.frequency(team1, key));// Get Key and value and count
}
将打印:关键:美国价值:5关键:巴塞罗那价值:6
如果你知道索引,这是可行的,至少在理论上是这样的:
System.out.println(team1.keySet().toArray()[0]);
keySet()
返回一个集合,因此您将该集合转换为数组。
当然,问题在于一套不承诺保留您的订单。如果你的HashMap中只有一个项目,那么你很好,但是如果你有更多,那么最好循环遍历地图,就像其他答案一样。
检查一下。
https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
(使用java.util.Objects.equals
,因为HashMap可以包含null
)
使用JDK8 +
/**
* Find any key matching a value.
*
* @param value The value to be matched. Can be null.
* @return Any key matching the value in the team.
*/
private Optional<String> getKey(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.findAny();
}
/**
* Find all keys matching a value.
*
* @param value The value to be matched. Can be null.
* @return all keys matching the value in the team.
*/
private List<String> getKeys(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
更“通用”,尽可能安全
/**
* Find any key matching the value, in the given map.
*
* @param mapOrNull Any map, null is considered a valid value.
* @param value The value to be searched.
* @param <K> Type of the key.
* @param <T> Type of the value.
* @return An optional containing a key, if found.
*/
public static <K, T> Optional<K> getKey(Map<K, T> mapOrNull, T value) {
return Optional.ofNullable(mapOrNull).flatMap(map -> map.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.findAny());
}
或者如果您使用的是JDK7。
private String getKey(Integer value){
for(String key : team1.keySet()){
if(Objects.equals(team1.get(key), value)){
return key; //return the first found
}
}
return null;
}
private List<String> getKeys(Integer value){
List<String> keys = new ArrayList<String>();
for(String key : team1.keySet()){
if(Objects.equals(team1.get(key), value)){
keys.add(key);
}
}
return keys;
}
您可以使用Map
方法检索所有keySet()
的键。现在,如果你需要的是获得一个给定价值的钥匙,这是一个完全不同的问题,Map
将无法帮助你;你需要一个专门的数据结构,比如来自Apache的BidiMap
的Commons Collections(允许在键和值之间进行双向查找的映射) - 还要注意几个不同的键可以映射到相同的值。
private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr= _map.entrySet().iterator();
//please check
while(itr.hasNext())
{
System.out.println("key of : "+itr.next().getKey()+" value of Map"+itr.next().getValue());
}
如果您想获得给定值(United
)的参数(5
),您也可以考虑使用双向映射(例如由Guava提供:http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html)。
如果您只是需要一些简单而且更需要验证的东西。
public String getKey(String key)
{
if(map.containsKey(key)
{
return key;
}
return null;
}
然后你可以搜索任何键。
System.out.println( "Does this key exist? : " + getKey("United") );
解决方案可以是,如果您知道键位置,将键转换为String数组并返回位置中的值:
public String getKey(int pos, Map map) {
String[] keys = (String[]) map.keySet().toArray(new String[0]);
return keys[pos];
}
试试这个简单的程序:
public class HashMapGetKey {
public static void main(String args[]) {
// create hash map
HashMap map = new HashMap();
// populate hash map
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
map.put(4, "four");
// get keyset value from map
Set keyset=map.keySet();
// check key set values
System.out.println("Key set values are: " + keyset);
}
}