> ## Content Index
> Fetch the complete content index at: https://lucent.blog/llms.txt
> Use this file to discover other available public pages before exploring further.

# java8如何排序Map
- URL: https://lucent.blog/java8ru-he-pai-xu-map/
- Published: 2020-06-25T10:30:36.000Z
- Updated: 2026-08-21T00:49:56.000Z
- Author: Lucent
- Tags: java, Stream API

在Java中，有多种方法可以对Map进行排序，但是我们将重点介绍Java 8 Stream，这是实现目标的一种非常优雅的方法。

### 学习一下HashMap的merge()函数

在学习Map排序之前，有必要讲一下HashMap的merge()函数，该函数应用场景就是当Key重复的时候，如何处理Map的元素值。这个函数有三个参数：

- 参数一：向map里面put的键
- 参数二：向map里面put的值
- 参数三：如果键发生重复，如何处理值。可以是一个函数，也可以写成lambda表达式。

```
String k = "key";
        HashMap<String, Integer> map = new HashMap<String, Integer>() {{
            put(k, 1);
        }};
        map.merge(k, 2, (oldVal, newVal) -> oldVal + newVal);

```

上面一段代码，首先创建了一个HashMap，并往里面放入了一个键值为k:1的元素。当我们调用merge函数，往map里面放入k:2键值对的时候，k键发生重复，就执行后面的lambda表达式。表达式的含义是：返回旧值oldVal加上新值newVal(1+2)，现在map里面只有一项元素那就是k:3。

### 按Map的键排序

下面一个例子使用Java 8 Stream按Map的键进行排序：

```
// 创建一个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);

```

看上文中第二段代码：

- 首先使用entrySet().stream() 将Map类型转换为Stream流类型。
- 然后使用sorted方法排序，排序的依据是Map.Entry.comparingByKey()，也就是按照Map的键排序
- 最后用collect方法将Stream流转成LinkedHashMap。 其他参数都好说，重点看第三个参数，就是一个merge规则的lambda表达式，与merge方法的第三个参数的用法一致。由于本例中没有重复的key，所以新值旧值随便返回一个即可。

上面的程序将在控制台上打印以下内容，键（国家/地区名称）以自然字母顺序排序：

```
China=86
France=33
Germany=49
Pakistan=92
United States=1

```

### 按Map的值排序

使用Stream API按其值对Map进行排序：

```
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);

```

结果：

```
United States=1
France=33
Germany=49
China=86
Pakistan=92

```

### 使用TreeMap按键排序

大家可能都知道`TreeMap`内的元素是有顺序的，所以利用`TreeMap`排序也是可取的一种方法。您需要做的就是创建一个`TreeMap`对象，并将数据从`HashMap`put到`TreeMap`中，非常简单：

```
// 将 `HashMap` 转为 `TreeMap`
Map<String, Integer> sorted = new TreeMap<>(codes);
sorted.entrySet().forEach(System.out::println);

```

结果：

```
China=86
France=33
Germany=49
Pakistan=92
United States=1

```

如上所示，键（国家/地区名称）以自然字母顺序排序。