48

鉴于 LinkedHashMap 包含字符串和整数,如何根据其值对 LinkedHashMap 进行排序。所以我需要根据整数值对其进行排序。非常感谢

4

4 回答 4

77
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> a, Map.Entry<String, Integer> b){
    return a.getValue().compareTo(b.getValue());
  }
});
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : entries) {
  sortedMap.put(entry.getKey(), entry.getValue());
}
于 2012-08-29T18:40:19.633 回答
43

现在使用 Java 8 流要容易得多:您不需要中间映射来排序:

map.entrySet().stream()
    .sorted(Map.Entry.comparingByValue())
    .forEach(entry -> ... );
于 2015-01-09T12:15:09.327 回答
4

LinkedHashMap只是维护插入顺序。如果要根据值进行排序,则可能需要编写自己的comparator.

于 2012-08-29T18:37:11.660 回答
1
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.NavigableMap;
import java.util.SortedMap;
import java.util.TreeMap;

public class HashMapTest {

public static void main(String[] args) {

    Map<String, Integer> map=new LinkedHashMap<String, Integer>();

    map.put("a", 11);
    map.put("B", 12);
    map.put("c", 3);
    map.put("d", 4);
    map.put("e", 5);
    map.put("f", 6);
    map.put("g", 7);
    map.put("h", 8);
    map.put("i", 9);
    map.put("j", 3);
    map.put("k", 2);
    map.put("l", 1);

    List<Map.Entry<String, Integer>> entries = new 
    ArrayList<Map.Entry<String, Integer>>(map.entrySet());
            Collections.sort(entries,new CustomizedHashMap());


            Map<String, Integer> sortedMap = new LinkedHashMap<String, 
   Integer>();
            for (Map.Entry<String, Integer> entry : entries) {
              sortedMap.put(entry.getKey(), entry.getValue());
              System.out.print( sortedMap.put(entry.getKey(), 
          entry.getValue())+"  ");
            }
     }
    }

 class CustomizedHashMap implements Comparator<Map.Entry<String, Integer>> {

  @Override
  public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
    // TODO Auto-generated method stub
    return -o1.getValue().compareTo(o2.getValue());
  }

}
于 2017-09-04T10:14:43.453 回答