First, what is Java 8 Stream
Use Java 8 Streams, buttons and we can sort by value of the map. Here's how it works:
- List Map or the like to convert a collection of object classes Stream object
- Streams of using
sorted()
the method to sort - Will eventually return to
LinkedHashMap
(sort order can be retained)
sorted()
Method Comparator
as a parameter, which can be sorted by any of the Map value type. If you are unfamiliar Comparator, you can see a few days before the articles in this number, there is an article devoted to the use of Comparator to sort List.
Second, learn about HashMap the merge () function
Before learning Map sort, it is necessary to talk about HashMap the merge () function, which scenario is when the Key repeat time, how to deal with the elements of value Map. This function takes three parameters:
- A parameter: map keys to put the inside
- Two parameters: the value of the put inside map
- Three parameters: If a duplicate key occurs, how to handle. May be a function, it can also be written as a lambda expression.
String k = "key";
HashMap<String, Integer> map = new HashMap<String, Integer>() {{
put(k, 1);
}};
map.merge(k, 2, (oldVal, newVal) -> oldVal + newVal);
See above section of code, we first create a HashMap, and entered into a key value for the k: element 1. When we call the merge function, to which map into the k: When key-value pairs 2, k key duplication, back on the implementation of the lambda expression. Expression means: returns the old value oldVal adding new value newVal (1 + 2), now there is only one map element that is k: 3.
In fact, a lambda expression is very simple: that anonymous function, parameter is the left arrow right arrow is a function of the body. Parameters and return values of the function type, the code is determined by the context.
Third, according to the Map key ordering
The following example uses a Java 8 Stream Map keys to sort by:
// 创建一个Map,并填入数据
Map<String, Integer> codes = new HashMap<>();
codes.put("United States", 1);
codes.put("Germany", 49);
codes.put("France", 33);
codes.put("China", 86);
codes.put("Pakistan", 92);
// 按照Map的键进行排序
Map<String, Integer> sortedMap = codes.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> oldVal,
LinkedHashMap::new
)
);
// 将排序后的Map打印
sortedMap.entrySet().forEach(System.out::println);
See paragraph 2 above in the code:
- First, using entrySet (). Stream () to convert the type Stream Map stream type.
- Then sorted according to the method, the sort that Map.Entry.comparingByKey (), which is in accordance Map key ordering
- Finally, collect method Stream flow into LinkedHashMap. Other parameters are hard to say, look at the focus of the third argument, lambda expression is a merge rule, consistent with the usage of the third parameter of the merge process. Since the present embodiment there are no duplicate key, so that the new value of a can not return to the old value.
The above program will print the following on the console keys (country / region name) natural alphabetical order:
China=86
France=33
Germany=49
Pakistan=92
United States=1
Please note that the use of
LinkedHashMap
the results to store ordered to maintain order. By default,Collectors.toMap()
returnHashMap
.HashMap
We can not guarantee the order of the elements.
If desired in reverse order according to the key, was added under red areas code.
Fourth, the sort of value Map
Of course, you can also use Stream API to Map sorted according to their values:
Map<String, Integer> sortedMap2 = codes.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldVal, newVal) -> oldVal,
LinkedHashMap::new));
sortedMap2.entrySet().forEach(System.out::println);
This is shown Map sorted by value output:
United States=1
France=33
Germany=49
China=86
Pakistan=92
Fifth, use the Sort button TreeMap
As you may know there are elements within the TreeMap order, so the use of a method TreeMap sort is desirable. You need to do is create an TreeMap
object and data HashMap
put into TreeMap
, it is very simple:
// 将 `HashMap` 转为 `TreeMap`
Map<String, Integer> sorted = new TreeMap<>(codes);
This is the output:
China=86
France=33
Germany=49
Pakistan=92
United States=1
As indicated above, the key (country / region name) alphabetically sorted natural.
Look forward to your attention
- Blogger recently wrote a book: "hand touch hand to teach you to learn SpringBoot series chapter 97 section -16"
- This article is reproduced indicate the source (en must not turn only the text): letters Gebo off .