
本教程操作环境:windows7系统、java10版,DELL G3电脑。
1.Map.Entry方法
把Map.Entry放进list,再用Comparator对list进行排序
1 2 3 4 | List list = new ArrayList(map.entrySet());
Collections.sort(list, (Entry e1, Entry e2)-> {
return e1.getKey().compareTo(e2.getKey());
});
|
实例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class SortKeysMapTest {
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put( "2010" , "jay" );
map.put( "1999" , "whx" );
map.put( "3010" , "huaxiao" );
List<Map.Entry<String,String>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (Map.Entry e1, Map.Entry e2)-> {
return e1.getKey().toString().compareTo(e2.getKey().toString());
});
for (Map.Entry entry : list) {
System.out.println( "key:" + entry.getKey() + ",value:" + entry.getValue());
}
}
}
|
2.TreeMap
TreeMap默认是升序的,如果我们需要改变排序方式,则需要使用比较器:Comparator。Comparator可以对集合对象或者数组进行排序的比较器接口,实现该接口的public compare(T o1,To2)方法即可实现排序,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import java.util.Comparator;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class TreeMapTest {
public static void main(String[] args) {
Map<String, String> map = new TreeMap<String, String>(
new Comparator<String>() {
public int compare(String obj1, String obj2) {
return obj2.compareTo(obj1);
}
});
map.put( "b" , "ccccc" );
map.put( "d" , "aaaaa" );
map.put( "c" , "bbbbb" );
map.put( "a" , "ddddd" );
Set<String> keySet = map.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
System.out.println(key + ":" + map.get(key));
}
}
}
|
运行结果如下:
1 2 3 4 | d:aaaaa
c:bbbbb
b:ccccc
a:ddddd
|
以上就是我们使用map排序的两种方法,在按值排序上一定要多下功夫,因为作为一个重点不免面试的时候有遇到的可能。更多Java学习指路:js教程