stream流对map的key排序
时间: 2023-11-17 12:56:06 浏览: 102
在Java 8中,可以使用Stream API对Map的key进行排序。具体实现可以使用Map.entrySet()方法获取Map中的所有键值对,然后使用Stream.sorted()方法对键值对进行排序,最后使用Collectors.toMap()方法将排序后的键值对重新放入一个新的Map中。
示例代码如下:
```
Map<String, Integer> map = new HashMap<>();
map.put("c", 3);
map.put("a", 1);
map.put("b", 2);
Map<String, Integer> sortedMap = map.entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
System.out.println(sortedMap);
```
输出结果为:{a=1, b=2, c=3}
相关问题
stream流 map 的key排序
在Java 8中,可以使用`sorted`方法对Map的key进行排序,然后再使用`forEach`方法遍历输出。
例如,假设有以下的Map数据:
```java
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 2);
map.put("orange", 4);
```
可以使用下面的代码对Map的key进行排序:
```java
map.keySet().stream()
.sorted()
.forEach(key -> System.out.println(key + " : " + map.get(key)));
```
输出结果为:
```
apple : 3
banana : 2
orange : 4
```
如果要对key进行倒序排序,则可以使用下面的代码:
```java
map.keySet().stream()
.sorted(Comparator.reverseOrder())
.forEach(key -> System.out.println(key + " : " + map.get(key)));
```
输出结果为:
```
orange : 4
banana : 2
apple : 3
```
Java 使用stream流根据Map的key对map进行排序
可以使用以下代码对Map按照key进行排序:
Map<String, Integer> map = new HashMap<>();
// 添加元素到map中
Map<String, Integer> sortedMap = map.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new));
阅读全文
相关推荐














