在Java中从HashMap获取密钥
我有一个Java的Hashmap,如下所示:在Java中从HashMap获取密钥,java,data-structures,java-6,Java,Data Structures,Java 6,我有一个Java的Hashmap,如下所示: private Map<String, Integer> team1 = new HashMap<String, Integer>(); team1.put("United", 5); 我怎样才能拿到钥匙?类似于:team1.getKey()返回“United”。AHashMap包含多个键。您可以使用keySet()获取所有键的集合 team1.put("foo", 1); team1.put("bar", 2); 将使
private Map<String, Integer> team1 = new HashMap<String, Integer>();
team1.put("United", 5);
我怎样才能拿到钥匙?类似于:
team1.getKey()
返回“United”。AHashMap
包含多个键。您可以使用keySet()
获取所有键的集合
team1.put("foo", 1);
team1.put("bar", 2);
将使用键“foo”
存储1
,使用键“bar”
存储2
。要迭代所有键,请执行以下操作:
for ( String key : team1.keySet() ) {
System.out.println( key );
}
将打印
“foo”
和“bar”
您可以使用该方法检索地图的所有键。现在,如果你需要得到一个给定值的键,那是完全不同的事情,Map
在这方面帮不了你;您需要一个专门的数据结构,如Apache中的(允许在键和值之间进行双向查找的映射)——还要注意,几个不同的键可以映射到同一个值。请检查此项
(使用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> findKey(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> findKeys(Integer value){
return team1
.entrySet()
.stream()
.filter(e -> Objects.equals(e.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
/**
*查找与值匹配的任何键。
*
*@param value要匹配的值。可以为空。
*@返回与团队中的值匹配的任何键。
*/
私有可选findKey(整数值){
返回队1
.entrySet()
.stream()
.filter(e->Objects.equals(e.getValue(),value))
.map(map.Entry::getKey)
.findAny();
}
/**
*查找与值匹配的所有键。
*
*@param value要匹配的值。可以为空。
*@返回团队中与值匹配的所有密钥。
*/
私有列表findKeys(整数值){
返回队1
.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> findKey(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());
}
/**
*在给定的映射中查找与该值匹配的任何键。
*
*@param mapOrNull任何映射,null被视为有效值。
*@param value要搜索的值。
*@param键的类型。
*@param值的类型。
*@如果找到,返回包含密钥的可选项。
*/
公共静态可选findKey(地图地图地图,T值){
返回可选的.ofNullable(mapOrNull).flatMap(map->map.entrySet())
.stream()
.filter(e->Objects.equals(e.getValue(),value))
.map(map.Entry::getKey)
.findAny());
}
或者如果您在JDK7上
private String findKey(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> findKeys(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;
}
私有字符串findKey(整数值){
for(字符串键:team1.keySet()){
if(Objects.equals(team1.get(key),value)){
return key;//返回找到的第一个
}
}
返回null;
}
私有列表findKeys(整数值){
列表键=新的ArrayList();
for(字符串键:team1.keySet()){
if(Objects.equals(team1.get(key),value)){
key.add(key);
}
}
返回键;
}
<>代码> < p>当你想得到赋值(<代码> 5代码>代码>)的参数(<代码>联合/代码>)时,你也可以考虑使用双向映射(例如,由番石榴提供的): 如果你只需要简单和更多的验证。
public String getKey(String key)
{
if(map.containsKey(key)
{
return key;
}
return null;
}
然后,您可以搜索任何键
System.out.println( "Does this key exist? : " + getKey("United") );
private Map\u Map=new HashMap();
迭代器itr=_map.entrySet().Iterator();
//请查收
while(itr.hasNext())
{
System.out.println(“key of:”+itr.next().getKey()+“Map值”+itr.next().getValue());
}
试试这个简单的程序:
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);
}
}
公共类MyHashMapKeys{
公共静态void main(字符串a[]{
HashMap hm=新的HashMap();
//将键值对添加到hashmap
hm.put(“第一”、“第一次插入”);
hm.put(“第二次”、“第二次插入”);
hm.put(“第三”、“第三次插入”);
系统输出打印项次(hm);
设置键=hm.keySet();
用于(字符串键:键){
系统输出打印项次(键);
}
}
}
这是可行的,至少在理论上是可行的,如果您知道索引:
System.out.println(team1.keySet().toArray()[0]);
keySet()
返回一个集合,因此可以将该集合转换为数组
当然,问题是,一套设备不能保证遵守您的订单。如果您的HashMap中只有一个项目,那么您就很好,但是如果您有更多的项目,那么最好像其他答案一样在地图上循环。我将要做的非常简单但浪费内存的事情是用一个键映射值,并使用一个值映射键,这样做:
private-Map-team1=new-HashMap()代码>
使用
非常重要,这样可以像这样映射键:值和值:键
team1.put(“联合”,5)代码>
team1.put(5,“联合”)代码>
因此,如果使用team1.get(“United”)=5和team1.get(5)=“United”
但是,如果你对一对中的一个对象使用某种特定的方法,我会更好地制作另一个贴图:
private-Map-team1=new-HashMap()代码>
private-Map-team1Keys=new-HashMap()代码>
然后
team1.put(“联合”,5)代码>
team1Keys.put(5,“联合”)代码>
记住,保持简单;) 获取键及其值
e、 g
private-Map-team1=new-HashMap();
第1组“联合”,第5组;
第1组:推杆(“巴塞罗那”,6);
for(字符串键:team1.keySet()){
System.out.println(“键:“+Key+”值:“+team1.get(Key)+”Count:“+Collections.frequency(team1,Key));//获取键、值和计数
}
将打印:键:联合值:5
Key:Barcelona Value:6如果知道键的位置,可以将键转换为字符串数组并返回位置中的值:
public String getKey(int pos, Map map) {
String[] keys = (String[]) map.keySet().toArray(new String[0]);
return keys[pos];
}
使用函数运算加快迭代
team1.keySet().forEach((键)->{
System.out.pri
System.out.println(team1.keySet().toArray()[0]);
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
}
public String getKey(int pos, Map map) {
String[] keys = (String[]) map.keySet().toArray(new String[0]);
return keys[pos];
}