如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?
当前回答
Lambda w/o使用外部库 一个键可以处理多个值(与BidiMap不同)
public static List<String> getKeysByValue(Map<String, String> map, String value) {
List<String> list = map.keySet().stream()
.collect(groupingBy(k -> map.get(k))).get(value);
return (list == null ? Collections.emptyList() : list);
}
获取一个包含键映射值的列表 对于1:1映射,返回的列表为空或包含1个值
其他回答
我认为keySet()可以很好地找到映射到值的键,并且具有比entrySet()更好的编码风格。
Ex:
假设你有一个HashMap映射,ArrayList res,一个你想找到所有映射到的键的值,然后存储到该res的键。
你可以编写如下代码:
for (int key : map.keySet()) {
if (map.get(key) == value) {
res.add(key);
}
}
而不是使用下面的entrySet():
for (Map.Entry s : map.entrySet()) {
if ((int)s.getValue() == value) {
res.add((int)s.getKey());
}
}
希望能有所帮助。
在java8
map.entrySet().stream().filter(entry -> entry.getValue().equals(value))
.forEach(entry -> System.out.println(entry.getKey()));
for(int key: hm.keySet()) {
if(hm.get(key).equals(value)) {
System.out.println(key);
}
}
虽然这并没有直接回答问题,但它是相关的。
这样你就不需要继续创建/迭代了。只需创建一个反向映射一次,就可以得到你需要的东西。
/**
* Both key and value types must define equals() and hashCode() for this to work.
* This takes into account that all keys are unique but all values may not be.
*
* @param map
* @param <K>
* @param <V>
* @return
*/
public static <K, V> Map<V, List<K>> reverseMap(Map<K,V> map) {
if(map == null) return null;
Map<V, List<K>> reverseMap = new ArrayMap<>();
for(Map.Entry<K,V> entry : map.entrySet()) {
appendValueToMapList(reverseMap, entry.getValue(), entry.getKey());
}
return reverseMap;
}
/**
* Takes into account that the list may already have values.
*
* @param map
* @param key
* @param value
* @param <K>
* @param <V>
* @return
*/
public static <K, V> Map<K, List<V>> appendValueToMapList(Map<K, List<V>> map, K key, V value) {
if(map == null || key == null || value == null) return map;
List<V> list = map.get(key);
if(list == null) {
List<V> newList = new ArrayList<>();
newList.add(value);
map.put(key, newList);
}
else {
list.add(value);
}
return map;
}
public class NewClass1 {
public static void main(String[] args) {
Map<Integer, String> testMap = new HashMap<Integer, String>();
testMap.put(10, "a");
testMap.put(20, "b");
testMap.put(30, "c");
testMap.put(40, "d");
for (Entry<Integer, String> entry : testMap.entrySet()) {
if (entry.getValue().equals("c")) {
System.out.println(entry.getKey());
}
}
}
}
一些额外的信息…可能对你有用
如果你的hashmap真的很大,上面的方法可能不太好。如果您的hashmap包含唯一键到唯一值的映射,您可以维护一个包含从值到键映射的hashmap。
也就是说你必须维护两个hashmap
1. Key to value
2. Value to key
在这种情况下,您可以使用第二个hashmap来获取key。
推荐文章
- 将枚举转换为集合/列表
- 在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忽略未映射的实例变量