2015-01-09 2 views
2

이것은 내 프로그램입니다. 아무도 내게 값에 따라지도의 키를 가져 오는 방법을 말해 줄 수 있습니까?값을 기반으로지도의 키를 얻는 방법

나는

String vendor_name = map.get("value"); 

으로 시도했지만 그 어떤 역 매핑이 없습니다

import java.util.Collections; 
import java.util.HashMap; 

public class Test { 

    public static void main(String args[]) { 

     HashMap<String, String> for_highest_price_vendor = new HashMap<String, String>(); 

     for_highest_price_vendor.put("vendor1", "20"); 
     for_highest_price_vendor.put("vendor2", "25"); 
     String maxValueInMap = (Collections.max(for_highest_price_vendor 
       .values())); // This will return max value in the Hashmap 

     String vendor_name = for_highest_price_vendor.get(maxValueInMap); 

     System.out.println(vendor_name); 

    } 

} 
+1

관련 항목 : http://stackoverflow.com/questions/1383797/java-hashmap-how-to-get-key-from-value – FourScore

+2

매핑은 한 가지 방법이므로 모든 키를 반복하여 매핑하면 매핑을 얻을 수 있습니다. 당신은 필요합니다 (그리고 KV 쌍이 1 : 1이라고 가정했습니다). – meskobalazs

+4

같은 값을 가진 두 개의 다른 키가 있다면? 어떤 열쇠를 갖고 싶습니까? –

답변

3

내가 널 returing.

항목을 반복하고 값을 원하는 값과 비교 한 다음 같으면 키를 가져옵니다.

물론 여러 키가 같은 값일 수 있습니다! 예를 들어

:

Map<String, String> foo = new HashMap<String, String>(); 
foo.put("foo", "bar"); 
for (Map.Entry<String, String> entry: foo.entrySet()) { 
    if (entry.getValue().equals("bar")) { 
     System.out.println(entry.getKey()); 
     break; // or not, you may want to add to a Collection and return it once the loop is completed 
    } 
} 
+6

매핑이 1 : 1이 아닌 경우 동일한 가치가있는 항목을 처리해야합니다! – meskobalazs

+0

@meskobalazs 예, 제 편집 참조. – Mena