map stream V排序
时间: 2023-09-03 19:14:41 浏览: 107
要对Map的Value进行排序,你可以使用Java 8的Stream API和Comparator。以下是一个示例代码:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;
public class MapSortByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("D", 5);
map.put("B", 3);
map.put("E", 6);
map.put("C", 2);
// 根据value倒序排序
Map<String, Integer> sortedMapDesc = map.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, HashMap::new));
// 根据value正序排序
Map<String, Integer> sortedMapAsc = map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(oldValue, newValue) -> oldValue, HashMap::new));
System.out.println("根据value倒序排序:");
sortedMapDesc.forEach((key, value) -> System.out.println(key + ": " + value));
System.out.println("根据value正序排序:");
sortedMapAsc.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
```
这段代码将打印出按照Value倒序排序和正序排序的结果。你可以根据自己的需求进行修改和使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Map和List排序,用Stream流实现](https://blog.csdn.net/u011731053/article/details/118757690)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [map stream流根据key排序](https://blog.csdn.net/a185589690/article/details/108034992)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [java8看不到源码-jcommon:我在项目中使用的常用工具、抽象和工具。它们使Java变得愉快](https://download.csdn.net/download/weixin_38522214/19392028)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文