2014-05-22 3 views
-3

I는 다음과 같은 항목이 <String, integer>을 포함하는 해시 맵,이 : 나는 그들이 하나의 큰 값을 찾아 다른 해시 맵에 저장 질문을 보았다해시 맵에 n 개의 최대 값을 찾기

("a",2) 
("ab", 3) 
("c",5) etc.. 

을,하지만 어떻게 "n"개의 가장 큰 숫자를 찾아서 결과 해시 맵에 넣을 수 있도록 반복 할 수 있습니까?

예를 들어 위의 hashmap 항목의 경우 n이 2이면 2 개의 가장 큰 값을 찾아서 결과 해시 맵에

("ab", 3) 
    ("c", 5) 

대단히 진보 해 주셔서 감사합니다.

+1

Welcome to Stackoverflow. 이 포럼의 목적은 당신이 프로그램하는 법을 배우고, 당신을 위해 일하지 않고 (재미를 제외하고) 도움을주는 것입니다. 당신은 무엇을 시도 했습니까? –

+1

@TAsk : 실제로 이것은 당신이 표시 한 질문과 중복 된 것이 아닙니다. 이 질문은 맵 반복과 관련이 적습니다. 실제로는 값 모음 내에서 N 개의 가장 큰 값을 찾는 방법과 관련이 있습니다. – WoDoSc

+0

이것을보십시오 : http://www.java2s.com/Code/Java/Collections-Data-Structure/Sortsmapbyvaluesinascendingorder.htm, 당신은 항목 집합을 얻고, 그것을 분류하고, 그 다음 첫 번째 n 항목을 추가하고 싶습니다. 정렬 된 항목이 새 맵으로 설정됩니다. – cowls

답변

1

은 아마이 할 수있는 가장 효율적인 방법이 아니다, 그러나 당신의 문제를 해결한다 :이 당신을 도울 것입니다 희망

static HashMap<String, Integer> nLargest(HashMap<String, Integer> map, int n) { //map and n largest values to search for 

    Integer value; 
    ArrayList<String> keys = new ArrayList<>(n); //to store keys of the n largest values 
    ArrayList<Integer> values = new ArrayList<>(n); //to store n largest values (same index as keys) 
    int index; 
    for (String key : map.keySet()) { //iterate on all the keys (i.e. on all the values) 
     value = map.get(key); //get the corresponding value 
     index = keys.size() - 1; //initialize to search the right place to insert (in a sorted order) current value within the n largest values 
     while (index >= 0 && value > values.get(index)) { //we traverse the array of largest values from smallest to biggest 
      index--; //until we found the right place to insert the current value 
     } 
     index = index + 1; //adapt the index (come back by one) 
     values.add(index, value); //insert the current value in the right place 
     keys.add(index, key); //and also the corresponding key 
     if (values.size() > n) { //if we have already found enough number of largest values 
      values.remove(n); //we remove the last largest value (i.e. the smallest within the largest) 
      keys.remove(n); //actually we store at most n+1 largest values and therefore we can discard just the last one (smallest) 
     } 
    } 
    HashMap<String, Integer> result = new HashMap<>(values.size()); 
    for (int i = 0; i < values.size(); i++) { //copy keys and value into an HashMap 
     result.put(keys.get(i), values.get(i)); 
    } 
    return result; 
} 

합니다.

관련 문제