Skip to content

Commit 7d2f675

Browse files
committed
使用Stream对map排序
1 parent 51848fc commit 7d2f675

File tree

3 files changed

+41
-3
lines changed

3 files changed

+41
-3
lines changed

src/main/java/com/xu/java8/Optional/Optional1.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,8 @@ public static void main(String[] args) {
3333
System.out.println(optional.orElse("fallback"));
3434
optional.ifPresent(System.out::println);
3535
optional2.ifPresent(System.out::println);
36+
37+
System.out.println(Optional.ofNullable(null).isPresent());
3638
}
3739
}
3840

src/main/java/com/xu/java8/Stream/Streams1.java

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
package com.xu.java8.Stream;
22

3-
import java.util.ArrayList;
4-
import java.util.List;
5-
import java.util.Optional;
3+
import java.util.*;
64

75
/**
86
* Class java8-Stream接口
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.xu.java8.Stream;
2+
3+
import java.util.HashMap;
4+
import java.util.LinkedHashMap;
5+
import java.util.Map;
6+
7+
/**
8+
* Created by xu on 2016/9/13.
9+
*/
10+
public class Streams6 {
11+
public static void main(String args[]) {
12+
Map<String, Integer> unsortMap = new HashMap<>();
13+
unsortMap.put("z", 10);
14+
unsortMap.put("b", 5);
15+
unsortMap.put("a", 6);
16+
unsortMap.put("c", 20);
17+
unsortMap.put("d", 1);
18+
unsortMap.put("e", 7);
19+
unsortMap.put("y", 8);
20+
unsortMap.put("n", 99);
21+
unsortMap.put("j", 50);
22+
unsortMap.put("m", 2);
23+
unsortMap.put("f", 9);
24+
System.out.println(sortByValue(unsortMap));
25+
}
26+
27+
/**
28+
* 使用stream类来对map的value排序(并行排序,逆序)
29+
*/
30+
public static <K, V extends Comparable<? super V>> Map<K, V>
31+
sortByValue(Map<K, V> map) {
32+
Map<K, V> result = new LinkedHashMap<>();
33+
map.entrySet().parallelStream().sorted((o1, o2) -> (o2.getValue()).compareTo(o1.getValue())).forEachOrdered(x ->
34+
result.put(x.getKey(), x
35+
.getValue()));
36+
return result;
37+
}
38+
}

0 commit comments

Comments
 (0)