如果我有值“foo”,和一个HashMap<String> ftw,其中ftw. containsvalue(“foo”)返回真,我怎么能得到相应的键?我需要遍历hashmap吗?最好的方法是什么?
当前回答
您可以将键、值对及其逆函数插入到映射结构中
map.put("theKey", "theValue");
map.put("theValue", "theKey");
使用map.get("theValue")将返回"theKey"。
这是一种快速而肮脏的方法,我已经创建了常量映射,它只适用于少数数据集:
只能包含1 ~ 1对 值集与键集不相交(1-> 2,2 ->3中断它)
其他回答
听起来最好的方法是使用map.entrySet()来遍历条目,因为map.containsValue()可能会这样做。
虽然这并没有直接回答问题,但它是相关的。
这样你就不需要继续创建/迭代了。只需创建一个反向映射一次,就可以得到你需要的东西。
/**
* 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;
}
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
public class M{
public static void main(String[] args) {
HashMap<String, List<String>> resultHashMap = new HashMap<String, List<String>>();
Set<String> newKeyList = resultHashMap.keySet();
for (Iterator<String> iterator = originalHashMap.keySet().iterator(); iterator.hasNext();) {
String hashKey = (String) iterator.next();
if (!newKeyList.contains(originalHashMap.get(hashKey))) {
List<String> loArrayList = new ArrayList<String>();
loArrayList.add(hashKey);
resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
} else {
List<String> loArrayList = resultHashMap.get(originalHashMap
.get(hashKey));
loArrayList.add(hashKey);
resultHashMap.put(originalHashMap.get(hashKey), loArrayList);
}
}
System.out.println("Original HashMap : " + originalHashMap);
System.out.println("Result HashMap : " + resultHashMap);
}
}
没有明确的答案,因为多个键可以映射到相同的值。如果要在自己的代码中强制执行唯一性,最好的解决方案是创建一个类,该类使用两个hashmap在两个方向上跟踪映射。
要找到映射到该值的所有键,请使用map. entryset()遍历hashmap中的所有对。
推荐文章
- 将枚举转换为集合/列表
- 在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忽略未映射的实例变量