2012-10-16 7 views
4

나는 HashMap을 다음 있습니다 :어떻게 값에 따라 HashMap의 요소를 정렬합니까?

HashMap<String, Integer> counts = new HashMap<String, Integer>(); 

값에 따라 주문하는 가장 간단한 방법은 무엇입니까?

+1

, 당신은 트리 맵을 사용할 수 있지만 키와 값이 있어야합니다. –

+0

이전 의견에서 권장 사항을 무시하십시오.그 문제는 항상 같은 수의 여러 항목이있을 가능성이 있으며지도에서 중복 키를 허용하지 않는다는 것입니다. 가장 좋은 점은 항목 목록 정렬에 대한 제안에 대한 답변을 따르는 것입니다. –

+0

'HashMap'을 사용하는 것에 국한되지 않는다면 단어를'String'으로 포함하는 클래스를 만들고,'int'로 카운트 한 다음, Comparable을 구현하여 최대 값을 찾으면 어떨까요? 이러한 모든 객체를 최대 힙에 삽입하고 힙의 루트 노드를 찾으십시오. –

답변

8

Map은 값순으로 정렬 할 수 없으며 특히 정렬 할 수없는 HashMap이 아닙니다.

대신, 당신은 항목을 정렬 할 수 있습니다

List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); 
Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { 
    public int compare(
     Map.Entry<String, Integer> entry1, Map.Entry<String, Integer> entry2) { 
    return entry1.getValue().compareTo(entry2.getValue()); 
    } 
}); 

횟수의 오름차순으로 항목을 정렬합니다.

0

순서대로 인쇄하려면 (저장하지 않음) 해결하십시오.

  1. 새로운지도 (tempMap)를 만들고 값으로 키와 키로 값을 넣어. 키를 고유하게 만들려면 각 키에 고유 한 값을 추가하십시오. key1 = value1 + @ 0.
  2. 는 지금 tempMap에서 해당 key를 얻을 수는 myVlues을 반복 myVlues

  3. 정렬 목록으로 map.values()Collections.sort(myVlues)

  4. myVlues 목록을 값의 목록을 가져 예를 들어, 키를 복원 key.substring (0, key.length-2) 키와 값 쌍을 출력하십시오.

희망이 있습니다.

1

TreeMapComparator으로 정의 된 순서로 항목을 유지할 수 있습니다.

  1. 가장 큰 값을 가장 먼저 두어 맵을 정렬하는 비교자를 만들 수 있습니다.
  2. 그런 다음 해당 Comparator를 사용하는 TreeMap을 작성합니다.
  3. 우리는 counts 맵에있는 모든 항목을 Comparator에 넣을 것입니다.
  4. 마지막으로지도에서 get the first key을 가장 많이 사용하는 단어 (또는 여러 단어의 수가 같은 경우 하나 이상 포함) 여야합니다.

    public class Testing { 
        public static void main(String[] args) { 
    
         HashMap<String,Double> counts = new HashMap<String,Integer>(); 
    
         // Sample word counts 
         counts.put("the", 100); 
         counts.put("pineapple",5); 
         counts.put("a", 50); 
    
         // Step 1: Create a Comparator that order by value with greatest value first 
         MostCommonValueFirst mostCommonValueFirst = new MostCommonValueFirst(counts); 
    
         // Step 2: Build a TreeMap that uses that Comparator 
         TreeMap<String,Double> sortedMap = new TreeMap<String,Integer (mostCommonValueFirst); 
    
         // Step 3: Populate TreeMap with values from the counts map 
         sortedMap.putAll(counts); 
    
         // Step 4: The first key in the map is the most commonly used word 
         System.out.println("Most common word: " + sortedMap.firstKey()); 
        } 
    } 
    
    private class MostCommonValueFirst implements Comparator<String> { 
        Map<String, Integer> base; 
    
        public MostCommonValueFirst(Map<String, Integer> base) { 
         this.base = base; 
        } 
    
        // Note: this comparator imposes orderings that are inconsistent with equals.  
        public int compare(String a, String b) { 
         if (base.get(a) >= base.get(b)) { 
          return 1; 
         } else { 
         return -1; 
         } // returning 0 would merge keys 
        } 
    } 
    

자료 : 귀하의 요구에 대한 다른 방법으로 주위를 당신은 HashMap의를 정렬 할 수 없습니다 https://stackoverflow.com/a/1283722/284685

+0

이것이 좋은 생각인지 잘 모르겠습니다. 키의 비교 자 순서는 맵의 값에 따라 변경 될 수 있습니다. 그것은 본질적으로 변경 가능한 키입니다 (TreeMap에 관한 한). –

+0

동의했다. 그러나 우리가지도를 채우고 난 후에 우리는 그것을 할 수있다. – Adam

관련 문제