2011-11-01 47 views
16

Tôi có HashMap này:Java loại HashMap bởi giá trị

HashMap<String, Integer> m 

mà cơ bản lưu trữ bất kỳ từ nào (String) và tần số của nó (số nguyên). Các mã sau đây được đặt hàng HashMap theo giá trị:

public static Map<String, Integer> sortByValue(Map<String, Integer> map) { 
     List<Map.Entry<String, Integer>> list = new LinkedList<Map.Entry<String, Integer>>(map.entrySet()); 

     Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() { 

      public int compare(Map.Entry<String, Integer> m1, Map.Entry<String, Integer> m2) { 
       return (m2.getValue()).compareTo(m1.getValue()); 
      } 
     }); 

     Map<String, Integer> result = new LinkedHashMap<String, Integer>(); 
     for (Map.Entry<String, Integer> entry : list) { 
      result.put(entry.getKey(), entry.getValue()); 
     } 
     return result; 
    } 

Bây giờ kịch bản đã thay đổi và tôi có điều này:

HashMap<String, doc>; 

class doc{ 
integer freq; 
HashMap<String, Double>; 
} 

Làm thế nào tôi có thể sắp xếp HashMap này bởi giá trị, sau phương pháp tương tự như sortByValue ?

Trả lời

5

Bạn cần phải tạo ra một so sánh tùy chỉnh như thế này:

import java.util.Comparator; 
import java.util.Arrays; 

public class Test { 
    public static void main(String[] args) { 
String[] strings = {"Here", "are", "some", "sample", "strings", "to", "be", "sorted"}; 

Arrays.sort(strings, new Comparator<String>() { 
    public int compare(String s1, String s2) { 
    int c = s2.length() - s1.length(); 
    if (c == 0) 
     c = s1.compareToIgnoreCase(s2); 
    return c; 
    } 
}); 

for (String s: strings) 
    System.out.print(s + " "); 
    } 
} 
+1

Er, ngoại trừ đó không phải là HashMap mặc dù .. –

1

@jackturky thay vì

public int compare(String s1, String s2) { 
    int c = s2.length() - s1.length(); 
    if (c == 0) 
     c = s1.compareToIgnoreCase(s2); 
    return c; 
    } 

tại sao không viết như (điều này tất nhiên kiểm tra rỗng và trống rỗng string)

public int compare(String s1, String s2) { 
      return s1.compareToIgnoreCase(s2); 
    } 
Các vấn đề liên quan