如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?
当前回答
据我所知,当你将HashMap的键和值表示为数组时,它们是不混合的:
hashmap.values().toArray()
and
hashmap.keySet().toArray()
所以下面的代码(从java 8开始)应该像预期的那样工作:
public Object getKeyByFirstValue(Object value) {
int keyNumber = Arrays.asList(hashmap.values().toArray()).indexOf(value);
return hashmap.keySet().toArray()[keyNumber];
}
然而,(警告!)它的工作速度比迭代慢2-3倍。
其他回答
让我们看看我的例子
Map<String, String> mapPeopleAndCountry = new HashMap<>();
mapPeopleAndCountry.put("Matis", "Lithuania");
mapPeopleAndCountry.put("Carlos", "Honduras");
mapPeopleAndCountry.put("Teboho", "Lesotho");
mapPeopleAndCountry.put("Marielos", "Honduras");
List<String> peopleInHonduras = mapPeopleAndCountry.keySet()
.stream()
.filter(r -> mapPeopleAndCountry.get(r)
.equals("Honduras"))
.stream(Collectors.toList());
// will return ["Carlos", "Marielos"]
注:未经测试,可能含有错别字
听起来最好的方法是使用map.entrySet()来遍历条目,因为map.containsValue()可能会这样做。
从Map中获取给定值的键的最简单实用方法:
public static void fetchValue(Map<String, Integer> map, Integer i)
{
Stream stream = map.entrySet().stream().filter(val-> val.getValue().equals(i)).map(Map.Entry::getKey);
stream.forEach(System.out::println);
}
详细解释:
方法fetchValue接受映射,该映射的键是String,值是Integer。 然后使用entryset().stream()将结果转换为流。 接下来,我们使用过滤器(中间操作),它会给我们一个等于第二个参数的值。 最后,我们使用forEach(最终操作)来打印最终结果。
public static String getKey(Map<String, Integer> mapref, String value) {
String key = "";
for (Map.Entry<String, Integer> map : mapref.entrySet()) {
if (map.getValue().toString().equals(value)) {
key = map.getKey();
}
}
return key;
}
用你自己的实现来装饰地图
class MyMap<K,V> extends HashMap<K, V>{
Map<V,K> reverseMap = new HashMap<V,K>();
@Override
public V put(K key, V value) {
// TODO Auto-generated method stub
reverseMap.put(value, key);
return super.put(key, value);
}
public K getKey(V value){
return reverseMap.get(value);
}
}
推荐文章
- 将枚举转换为集合/列表
- 在Java中创建对象数组
- Java中字符串的字节数
- IntelliJ IDEA with Junit 4.7”!!JUnit 3.8或更高版本:
- 既然JavaScript和Java没有任何关系,它为什么被称为JavaScript ?
- 番石榴vs Apache Commons
- Java是编译型编程语言还是解释型编程语言?
- 我如何通过Java应用程序使用GMail,雅虎或Hotmail发送电子邮件?
- 注释@GetMapping和@RequestMapping(method = RequestMethod.GET)之间的区别
- lambda表达式中使用的变量应该是final或有效final
- 如何创建数组列表的数组?
- noclassdeffounderror:无法初始化类XXX
- 如何创建今天午夜和明天午夜的Java日期对象?
- ByteBuffer在Java中的用途是什么?
- 使Hibernate忽略未映射的实例变量