Java Hashmap:如何从值中获取键?
如果我有值Java Hashmap:如何从值中获取键?,java,hashmap,Java,Hashmap,如果我有值“foo”,并且有一个HashMap ftw,其中ftw.containsValue(“foo”)返回true,我如何获得相应的键?我必须循环使用hashmap吗?最好的方法是什么?没有明确的答案,因为多个键可以映射到同一个值。如果要用自己的代码强制实现唯一性,最好的解决方案是创建一个类,该类使用两个hashmap在两个方向上跟踪映射。要查找映射到该值的所有键,请使用map.entrySet()遍历hashmap中的所有对听起来最好的方法是使用map.entrySet()对条目进行迭代
“foo”
,并且有一个HashMap ftw
,其中ftw.containsValue(“foo”)
返回true
,我如何获得相应的键?我必须循环使用hashmap吗?最好的方法是什么?没有明确的答案,因为多个键可以映射到同一个值。如果要用自己的代码强制实现唯一性,最好的解决方案是创建一个类,该类使用两个hashmap在两个方向上跟踪映射。要查找映射到该值的所有键,请使用map.entrySet()遍历hashmap中的所有对
听起来最好的方法是使用map.entrySet()
对条目进行迭代,因为map.containsValue()
可能会这样做。如果您选择使用而不是标准Java Collections框架,您可以轻松实现这一点
集合库中的接口是一个双向映射,允许您将一个键映射到一个值(如普通映射),还可以将一个值映射到一个键,从而允许您在两个方向上执行查找。该方法支持获取值的键
但是有一个警告,bidi映射不能有多个值映射到键,因此除非数据集在键和值之间有1:1的映射,否则不能使用bidi映射
如果您希望依赖Java Collections API,那么在将值插入映射时,必须确保键和值之间的1:1关系。这说起来容易做起来难 一旦可以确保,请使用该方法获取映射中的条目集(映射)。获得类型为的集合后,遍历条目,将值与预期值进行比较,然后获得
可以在和重构库(后者不是Apache项目)中找到对具有泛型的bidi映射的支持。感谢Esko指出Apache Commons集合中缺少的通用支持。将集合与泛型一起使用可以使代码更易于维护
自从正式的Apache Commons集合™ 图书馆支持
请参阅“org.apache.commons.collections4.bidimap”包的页面,以获取当前支持Java泛型的可用实现和接口的列表
- 使用为此而构建的地图实现,如来自google collections的。请注意,google collections BiMap需要唯一的值和键,但它在两个方面都提供了高性能
- 手动维护两个映射-一个用于键->值,另一个用于值->键
- 遍历
并查找与该值匹配的键。这是最慢的方法,因为它需要遍历整个集合,而其他两个方法不需要entrySet()
public class KeyValue {
public Object key;
public Object value;
public KeyValue(Object key, Object value) { ... }
}
map.put(key, new KeyValue(key, value));
然后,当你有一个值时,你也有键。是的,你必须在hashmap中循环,除非你按照这些不同答案的建议实现了一些东西。与其摆弄entrySet,我只需要获取keySet(),在该集合上迭代,并保留获取匹配值的(第一个)键。如果您需要所有与该值匹配的键,显然您必须完成全部工作 正如Jonas所建议的,这可能已经是containsValue方法正在做的事情了,所以您可以一起跳过该测试,每次都进行迭代(或者编译器可能已经消除了冗余,谁知道呢) 另外,相对于其他答案,如果你的反向地图看起来像
Map<Value, Set<Key>>
Map
如果您需要该功能,您可以处理非唯一的键->值映射(将它们放在一边)。这将很好地结合到人们建议使用两个映射的任何解决方案中。如果您的数据结构在键和值之间有多对一映射,您应该迭代条目并选择所有合适的键:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
公共静态设置getKeysByValue(映射映射,E值){
Set keys=new HashSet();
for(条目:map.entrySet()){
if(Objects.equals(value,entry.getValue())){
key.add(entry.getKey());
}
}
返回键;
}
如果是一对一关系,您可以返回第一个匹配的键:
public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
return entry.getKey();
}
}
return null;
}
public static T getKeyByValue(映射映射,E值){
for(条目:map.entrySet()){
if(Objects.equals(value,entry.getValue())){
return entry.getKey();
}
}
返回null;
}
在Java 8中:
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
return map.entrySet()
.stream()
.filter(entry -> Objects.equals(entry.getValue(), value))
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
}
公共静态设置getKeysByValue(映射映射,E值){
return map.entrySet()
.stream()
.filter(entry->Objects.equals(entry.getValue(),value))
.map(map.Entry::getKey)
.collect(收集器.toSet());
}
此外,对于番石榴用户来说,这可能是有用的。例如:
BiMap<Token, Character> tokenToChar =
ImmutableBiMap.of(Token.LEFT_BRACKET, '[', Token.LEFT_PARENTHESIS, '(');
Token token = tokenToChar.inverse().get('(');
Character c = tokenToChar.get(token);
BiMap tokenToChar=
ImmutableBiMap.of(Token.LEFT_括号,“[”,Token.LEFT_括号,“(”);
Token-Token=tokenToChar.inverse().get('(');
字符c=tokenToChar.get(令牌);
恐怕您只需迭代地图即可。我能想到的最短方法是:
Iterator<Map.Entry<String,String>> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String,String> entry = iter.next();
if (entry.getValue().equals(value_you_look_for)) {
String key_you_look_for = entry.getKey();
}
}
Iterator iter=map.entrySet().Iterator();
while(iter.hasNext()){
Map.Entry=iter.next();
if(entry.getValue().equals(您要查找的值)){
String key_you_look_for=entry.getKey();
}
}
您可以使用以下代码使用值获取密钥
ArrayList valuesList = new ArrayList();
Set keySet = initalMap.keySet();
ArrayList keyList = new ArrayList(keySet);
for(int i = 0 ; i < keyList.size() ; i++ ) {
valuesList.add(initalMap.get(keyList.get(i)));
}
Collections.sort(valuesList);
Map finalMap = new TreeMap();
for(int i = 0 ; i < valuesList.size() ; i++ ) {
String value = (String) valuesList.get(i);
for( int j = 0 ; j < keyList.size() ; j++ ) {
if(initalMap.get(keyList.get(j)).equals(value)) {
finalMap.put(keyList.get(j),value);
}
}
}
System.out.println("fianl map ----------------------> " + finalMap);
ArrayList valuesList=new ArrayList();
Set keySet=initalMap.keySet();
ArrayList键列表=新的ArrayList(键集);
对于(int i=0;ipublic 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());
}
}
}
}
1. Key to value
2. Value to key
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class HMap<K, V> {
private final Map<K, Map<K, V>> map;
public HMap() {
map = new HashMap<K, Map<K, V>>();
}
public HMap(final int initialCapacity) {
map = new HashMap<K, Map<K, V>>(initialCapacity);
}
public boolean containsKey(final Object key) {
return map.containsKey(key);
}
public V get(final Object key) {
final Map<K, V> entry = map.get(key);
if (entry != null)
return entry.values().iterator().next();
return null;
}
public K getKey(final Object key) {
final Map<K, V> entry = map.get(key);
if (entry != null)
return entry.keySet().iterator().next();
return null;
}
public V put(final K key, final V value) {
final Map<K, V> entry = map
.put(key, Collections.singletonMap(key, value));
if (entry != null)
return entry.values().iterator().next();
return null;
}
}
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);
}
}
public static class SmartHashMap <T1 extends Object, T2 extends Object> {
public HashMap<T1, T2> keyValue;
public HashMap<T2, T1> valueKey;
public SmartHashMap(){
this.keyValue = new HashMap<T1, T2>();
this.valueKey = new HashMap<T2, T1>();
}
public void add(T1 key, T2 value){
this.keyValue.put(key, value);
this.valueKey.put(value, key);
}
public T2 getValue(T1 key){
return this.keyValue.get(key);
}
public T1 getKey(T2 value){
return this.valueKey.get(value);
}
}
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
public class ValueKeysMap<K, V> extends HashMap <K,V>{
HashMap<V, Set<K>> ValueKeysMap = new HashMap<V, Set<K>>();
@Override
public boolean containsValue(Object value) {
return ValueKeysMap.containsKey(value);
}
@Override
public V put(K key, V value) {
if (containsValue(value)) {
Set<K> keys = ValueKeysMap.get(value);
keys.add(key);
} else {
Set<K> keys = new HashSet<K>();
keys.add(key);
ValueKeysMap.put(value, keys);
}
return super.put(key, value);
}
@Override
public V remove(Object key) {
V value = super.remove(key);
Set<K> keys = ValueKeysMap.get(value);
keys.remove(key);
if(keys.size() == 0) {
ValueKeysMap.remove(value);
}
return value;
}
public Set<K> getKeys4ThisValue(V value){
Set<K> keys = ValueKeysMap.get(value);
return keys;
}
public boolean valueContainsThisKey(K key, V value){
if (containsValue(value)) {
Set<K> keys = ValueKeysMap.get(value);
return keys.contains(key);
}
return false;
}
/*
* Take care of argument constructor and other api's like putAll
*/
}
map.put("theKey", "theValue");
map.put("theValue", "theKey");
map.entrySet().stream().filter(entry -> entry.getValue().equals(value))
.forEach(entry -> System.out.println(entry.getKey()));
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] argv) {
Map<String, String> map = new HashMap<String, String>();
map.put("1","one");
map.put("2","two");
map.put("3","three");
map.put("4","four");
System.out.println(getKeyFromValue(map,"three"));
}
// hm is the map you are trying to get value from it
public static Object getKeyFromValue(Map hm, Object value) {
for (Object o : hm.keySet()) {
if (hm.get(o).equals(value)) {
return o;
}
}
return null;
}
}
getKeyFromValue(hashMap, item);
System.out.println("getKeyFromValue(hashMap, item): "+getKeyFromValue(hashMap, item));
/**
* This method gets the Key for the given Value
* @param paramName
* @return
*/
private String getKeyForValueFromMap(String paramName) {
String keyForValue = null;
if(paramName!=null)) {
Set<Entry<String,String>> entrySet = myMap().entrySet();
if(entrySet!=null && entrySet.size>0) {
for(Entry<String,String> entry : entrySet) {
if(entry!=null && paramName.equalsIgnoreCase(entry.getValue())) {
keyForValue = entry.getKey();
}
}
}
}
return keyForValue;
}
for(int key: hm.keySet()) {
if(hm.get(key).equals(value)) {
System.out.println(key);
}
}
ftw.forEach((key, value) -> {
if (value.equals("foo")) {
System.out.print(key);
}
});
public <K, V> K getKeyByValue(Map<K, V> map, V value) {
for (Map.Entry<K, V> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
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);
}
}
String[] keys = yourMap.keySet().toArray(new String[0]);
for(int i = 0 ; i < keys.length ; i++){
//This is your key
String key = keys[i];
//This is your value
yourMap.get(key)
}
public class HashmapKeyExist {
public static void main(String[] args) {
HashMap<String, String> hmap = new HashMap<String, String>();
hmap.put("1", "Bala");
hmap.put("2", "Test");
Boolean cantain = hmap.containsValue("Bala");
if(hmap.containsKey("2") && hmap.containsValue("Test"))
{
System.out.println("Yes");
}
if(cantain == true)
{
System.out.println("Yes");
}
Set setkeys = hmap.keySet();
Iterator it = setkeys.iterator();
while(it.hasNext())
{
String key = (String) it.next();
if (hmap.get(key).equals("Bala"))
{
System.out.println(key);
}
}
}
}
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;
}
for (int key : map.keySet()) {
if (map.get(key) == value) {
res.add(key);
}
}
for (Map.Entry s : map.entrySet()) {
if ((int)s.getValue() == value) {
res.add((int)s.getKey());
}
}
/**
* 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;
}