0%

Java对map集合排序

对 key 排序

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
28
29
30
31
32
33
34
35
36
import java.util.*;

public class Main {

// 对 map 集合按照key排序的方式来进行排序打印
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("张三","99");
map.put("aa","53");
map.put("王五","59");
map.put("ca","51");
map.put("bw","52");

Map<String,String> treeMap = new TreeMap<>(new MyComparator());
treeMap.putAll(map);

Set<String> sets = treeMap.keySet();
Iterator<String> iterator = sets.iterator();
while (iterator.hasNext()){
String key = iterator.next();
System.out.println(key + "--" + map.get(key));
}
}

/**
* 重写比较器的compare方法
*/
static class MyComparator implements Comparator<String>{

@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
}
}

对 value 排序

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
28
29
30
31
32
import java.util.*;

public class Main {

// 对 map 集合按照value排序的方式来进行排序打印
public static void main(String[] args) {
Map<String,String> map = new HashMap<>();
map.put("张三","99");
map.put("aa","53");
map.put("王五","59");
map.put("ca","51");
map.put("bw","52");

List<Map.Entry<String, String>> list = new ArrayList<>(map.entrySet());
Collections.sort(list,new MyComparator());

for (Map.Entry<String,String> entry : list){
System.out.println(entry.getKey() + " -- " + entry.getValue());
}
}

/**
* 重写比较器的compare方法
*/
static class MyComparator implements Comparator<Map.Entry>{
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
return ((String)o1.getValue()).compareTo((String) o2.getValue());
}
}
}