IT박스

Java의 HashMap에서 키 가져 오기

itboxs 2020. 6. 13. 19:30
반응형

Java의 HashMap에서 키 가져 오기


다음과 같은 Java 해시 맵이 있습니다.

private Map<String, Integer> team1 = new HashMap<String, Integer>();

그런 다음 다음과 같이 채 웁니다.

team1.put("United", 5);

열쇠는 어떻게 줍니까? 같은 뭔가 : team1.getKey()"미국"을 반환합니다.


A HashMap는 둘 이상의 키를 포함합니다. keySet()모든 키 세트를 얻는 데 사용할 수 있습니다 .

team1.put("foo", 1);
team1.put("bar", 2);

저장할 1"foo"2"bar". 모든 키를 반복하려면 :

for ( String key : team1.keySet() ) {
    System.out.println( key );
}

인쇄됩니다 "foo""bar".


인덱스를 알고 있다면 이론 상으로는 가능 합니다.

System.out.println(team1.keySet().toArray()[0]);

keySet() 집합을 반환하므로 집합을 배열로 변환합니다.

물론 문제는 세트가 주문을 유지할 것을 약속하지 않는다는 것입니다. HashMap에 하나의 항목 만 있으면 좋을 것입니다.하지만 그보다 많으면 다른 답변과 마찬가지로 맵을 반복하는 것이 가장 좋습니다.


이것을 확인하십시오.

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

( java.util.Objects.equalsHashMap은를 포함 할 수 있기 때문에 사용 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> getKey(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> getKeys(Integer value){
    return team1
        .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> getKey(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());
}

또는 JDK7을 사용중인 경우.

private String getKey(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> getKeys(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;
}

Map메소드를 사용하여 모든 키를 검색 할 수 있습니다 keySet(). 만약 당신이 필요로하는 것이 그것의 가치가 주어진 를 얻는 것이라면 , 그것은 완전히 다른 문제이며 당신에게 도움이되지 않을 것입니다; Apache의 Commons Collections 에서 (키와 값 사이의 양방향 조회를 허용하는 맵) 과 같은 특수한 데이터 구조가 필요합니다. 또한 여러 다른 키가 동일한 값에 매핑 될 수 있습니다.MapBidiMap


간단하고 검증이 필요한 것이 있다면.

public String getKey(String key)
{
    if(map.containsKey(key)
    {
        return key;
    }
    return null;
}

그런 다음 아무 키나 검색 할 수 있습니다.

System.out.println( "Does this key exist? : " + getKey("United") );

private Map<String, Integer> _map= new HashMap<String, Integer>();
Iterator<Map.Entry<String,Integer>> itr=  _map.entrySet().iterator();
                //please check 
                while(itr.hasNext())
                {
                    System.out.println("key of : "+itr.next().getKey()+" value of      Map"+itr.next().getValue());
                }

As you would like to get argument (United) for which value is given (5) you might also consider using bidirectional map (e.g. provided by Guava: http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/BiMap.html).


A solution can be, if you know the key position, convert the keys into an String array and return the value in the position:

public String getKey(int pos, Map map) {
    String[] keys = (String[]) map.keySet().toArray(new String[0]);

    return keys[pos];
}

Try this simple program:

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);
   }    
}

public class MyHashMapKeys {

    public static void main(String a[]){
        HashMap<String, String> hm = new HashMap<String, String>();
        //add key-value pair to hashmap
        hm.put("first", "FIRST INSERTED");
        hm.put("second", "SECOND INSERTED");
        hm.put("third","THIRD INSERTED");
        System.out.println(hm);
        Set<String> keys = hm.keySet();
        for(String key: keys){
            System.out.println(key);
        }
    }
}

What I'll do which is very simple but waste memory is to map the values with a key and do the oposite to map the keys with a value making this:

private Map<Object, Object> team1 = new HashMap<Object, Object>();

it's important that you use <Object, Object> so you can map keys:Value and Value:Keys like this

team1.put("United", 5);

team1.put(5, "United");

So if you use team1.get("United") = 5 and team1.get(5) = "United"

But if you use some specific method on one of the objects in the pairs I'll be better if you make another map:

private Map<String, Integer> team1 = new HashMap<String, Integer>();

private Map<Integer, String> team1Keys = new HashMap<Integer, String>();

and then

team1.put("United", 5);

team1Keys.put(5, "United");

and remember, keep it simple ;)


To get Key and its value

e.g

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
                }

Will print: Key: United Value:5 Key: Barcelona Value:6

참고URL : https://stackoverflow.com/questions/10462819/get-keys-from-hashmap-in-java

반응형