jdk8之map排序

JDK8之Map排序

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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
public class  {


* JDK8
* 按照Key排序
*
* @param map map数据
* @param asc 是否升序
* @param <K> Key
* @param <V> Value
* @return Map<K, V>
*/
private static <K extends Comparable<? super K>, V> Map<K, V> sortByKey(Map<K, V> map, boolean asc) {
Map<K, V> result = new LinkedHashMap<>();
Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
if (asc) {
stream.sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else {
stream.sorted(Map.Entry.<K, V>comparingByKey().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}


* JDK8
* 按照Value排序
*
* @param map map数据
* @param asc 是否升序
* @param <K> Key
* @param <V> Value
* @return Map<K, V>
*/
private static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map, boolean asc) {
Map<K, V> result = new LinkedHashMap<>();
Stream<Map.Entry<K, V>> stream = map.entrySet().stream();
if (asc) //升序
{
stream.sorted(Map.Entry.comparingByValue()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
} else //降序
{
stream.sorted(Map.Entry.<K, V>comparingByValue().reversed()).forEachOrdered(e -> result.put(e.getKey(), e.getValue()));
}
return result;
}


* 使用 Map按key进行排序
*/
public static String sortMapByKey(HashMap<String, String> map) {

Set<String> keySet = map.keySet();

String[] keyArray = keySet.toArray(new String[0]);

Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (String k : keyArray) {
if (map.get(k).trim().length() > 0) // 参数值为空,则不参与签名
sb.append(k).append("=").append(map.get(k).trim()).append("&");
}
return sb.toString().substring(0, sb.length() - 1);
}

public static void main(String[] args) {

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

map.put("b", 44);
map.put("a", 22);
map.put("c", 11);

System.out.println(map);

System.out.println(sortByKey(map, true));

System.out.println(sortByValue(map, false));
}
}