java Map<String,List<String>> 根据list的值排序,lamda表达式
时间: 2024-03-12 09:40:27 浏览: 19
在Java中,你可以使用`Map`的`entrySet()`方法来获取所有的键值对,然后使用`Stream`和`Lambda表达式`对这些键值对进行排序。这里有一个例子,它根据`List<String>`中的字符串长度对Map进行排序:
```java
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<>();
map.put("One", Arrays.asList("One", "Two", "Three"));
map.put("Two", Arrays.asList("Four", "Five"));
map.put("Three", Arrays.asList("Six"));
// 使用Lambda表达式和Stream排序
Map<String, List<String>> sortedMap =
map.entrySet().stream()
.sorted(Map.Entry.<String, List<String>>comparingByValue())
.collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(oldValue, newValue) -> oldValue, LinkedHashMap::new)); // 使用LinkedHashMap保持插入顺序
sortedMap.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
```
在这个例子中,我们首先创建了一个`Map`,其中键是字符串,值是另一个字符串列表。然后我们使用`stream()`方法来获取一个流,再使用`sorted()`方法对流中的键值对进行排序。排序的依据是列表中的字符串长度。最后,我们使用`collect()`方法将流中的元素收集到一个新的`Map`中。这个新的`Map`就是排序后的结果。
注意,这个例子使用了Java 8的特性,包括Lambda表达式和Stream API。如果你的环境不支持这些特性,你可能需要使用不同的方法来对Map进行排序。