IT박스

HashMap-첫 번째 키 값 얻기

itboxs 2020. 8. 26. 07:41
반응형

HashMap-첫 번째 키 값 얻기


다음은 HashMap에 포함 된 값입니다.

statusName {Active=33, Renewals Completed=3, Application=15}

첫 번째 키 (즉, 활성)를 얻기위한 Java 코드

Object myKey = statusName.keySet().toArray()[0];

첫 번째 키 "값"(예 : 33)을 수집하려면 어떻게해야합니까? "키"와 "값"을 별도의 변수에 저장하고 싶습니다.


이것을 시도 할 수 있습니다.

 Map<String,String> map = new HashMap<>();
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key = entry.getKey();
 String value = entry.getValue();

명심 HashMap삽입 순서를 보장하지 않습니다. LinkedHashMap주문을 그대로 유지 하려면 a 사용하십시오 .

예 :

 Map<String,String> map = new LinkedHashMap<>();
 map.put("Active","33");
 map.put("Renewals Completed","3");
 map.put("Application","15");
 Map.Entry<String,String> entry = map.entrySet().iterator().next();
 String key= entry.getKey();
 String value=entry.getValue();
 System.out.println(key);
 System.out.println(value);

산출:

 Active
 33

"첫 번째"값을 얻으려면 :

map.values().toArray()[0]

"첫 번째"키의 값을 얻으려면 :

map.get(map.keySet().toArray()[0])

참고 : 위 코드는 테스트를 거쳐 작동합니다.

HashMap 항목이 정렬되지 않았기 때문에 "처음"이라고 말합니다.

그러나 LinkedHashMap은 삽입 된 순서대로 항목을 반복합니다. 삽입 순서가 중요한 경우 맵 구현에 사용할 수 있습니다.


자바 8 방식,

String firstKey = map.keySet().stream().findFirst().get();


첫 번째 항목 전체를 얻기 위해 이것을 시도 할 수도 있습니다.

Map.Entry<String, String> entry = map.entrySet().stream().findFirst().get();
String key = entry.getKey();
String value = entry.getValue();

첫 번째 항목의 키만 가져 오려면

String key = map.entrySet().stream().map(Map.Entry::getKey).findFirst().get();
// or better
String key = map.keySet().stream().findFirst().get();

이것은 첫 번째 항목의 값만 가져옵니다.

String value = map.entrySet().stream().map(Map.Entry::getValue).findFirst().get();
// or better
String value = map.values().stream().findFirst().get();

또한, 당신이 무엇을하고 있는지 알고 있고 맵의 두 번째 항목 (세 번째 항목과 동일)을 얻고 싶다면 이것을 시도해야합니다.

Map.Entry<String, String> entry = map.entrySet().stream().skip(1).findFirst().get();
String key = map.keySet().stream().skip(1).findFirst().get();
String value = map.values().stream().skip(1).findFirst().get();

첫 번째 키 "값"(예 : 33)을 수집하는 방법

를 사용 youMap.get(keyYouHave)하면 그 가치를 얻을 수 있습니다.

"키"와 "값"을 별도의 변수에 저장하려는 경우

예, 변수에 할당 할 수 있습니다.

잠깐만 ......... 끝나지 않았습니다.

당신 (비즈니스 로직)이 삽입과 검색의 순서에 의존한다면 이상한 결과를 보게 될 것입니다. 지도는 주문되지 않으며 주문에 저장되지 않습니다. 그 사실에 유의하십시오. 주문을 보존하려면 다른 방법을 사용하십시오. 아마LinkedHashMap


일반적으로지도에서는 ​​게재 신청서가 존중되지 않습니다. 이 시도 :

    /**
     * Get the first element of a map. A map doesn't guarantee the insertion order
     * @param map
     * @param <E>
     * @param <K>
     * @return
     */
    public static <E,K> K getFirstKeyValue(Map<E,K> map){
        K value = null;
        if(map != null && map.size() > 0){
            Map.Entry<E,K> entry =  map.entrySet().iterator().next();
            if(entry != null)
                value = entry.getValue();
        }
        return  value;
    }

I use this only when I am sure that that map.size() == 1 .


Note that you should note that your logic flow must never rely on accessing the HashMap elements in some order, simply put because HashMaps are not ordered Collections and that is not what they are aimed to do. (You can read more about odered and sorter collections in this post).

Back to the post, you already did half the job by loading the first element key:

Object myKey = statusName.keySet().toArray()[0];

Just call map.get(key) to get the respective value:

Object myValue = statusName.get(myKey);

Improving whoami's answer. Since findFirst() returns an Optional, it is a good practice to check if there is a value.

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSet is unreliable. But sometimes we have HashMap pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.


You can also try below:

Map.Entry<String, Integer> entry = myMap.firstEntry();
System.out.println("First Value = " + entry);

참고URL : https://stackoverflow.com/questions/26230225/hashmap-getting-first-key-value

반응형