java8中list转map并排序
时间: 2023-10-25 19:13:27 浏览: 64
假设你有一个`List`对象,其中包含`Person`对象,每个`Person`对象都有一个唯一的`id`属性和一个`name`属性。现在你想将这个`List`转换为一个`Map`,其中`id`属性作为键,`Person`对象本身作为值,并按照`name`属性对Map进行排序。可以按照如下方式实现:
```java
List<Person> personList = ... // 假设这是你的Person对象列表
Map<Integer, Person> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Function.identity()))
.entrySet().stream()
.sorted(Map.Entry.comparingByValue(Comparator.comparing(Person::getName)))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
```
上述代码使用Java 8中的`Stream` API先将`List`转换为`Map`,然后使用`sorted`方法根据`Person`对象的`name`属性排序,并最终将结果收集到`LinkedHashMap`中以保留排序顺序。
相关问题
list转map并排序
可以使用Java8中的Stream API和Collectors.toMap()方法将List转换为Map,并使用Comparator对Map进行排序。以下是一个示例代码:
```java
import java.util.*;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
// 创建一个Person列表
List<Person> personList = Arrays.asList(
new Person(1, "Alice"),
new Person(2, "Bob"),
new Person(3, "Charlie")
);
// 将Person列表转换为Map,并按照id排序
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName, (oldValue, newValue) -> oldValue, TreeMap::new));
// 输出排序后的Map
System.out.println(personMap);
}
}
class Person {
private int id;
private String name;
public Person(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
```
输出结果为:
```
{1=Alice, 2=Bob, 3=Charlie}
```
在上面的示例代码中,我们首先创建了一个Person列表,然后使用Stream API和Collectors.toMap()方法将其转换为Map。在toMap()方法中,我们使用Person对象的id作为Map的键,使用Person对象的name作为Map的值。我们还传递了一个合并函数,以便在遇到重复键时保留旧值。最后,我们使用TreeMap对Map进行排序,以确保按照id排序。
java对list中的map进行排序
可以使用Java 8及以上版本中的lambda表达式和Comparator接口来对List中的Map进行排序。以下是一个示例代码:
```java
List<Map<String, Object>> list = new ArrayList<>();
// 添加Map到List中
// 按照Map中的某个key进行升序排序
list.sort(Comparator.comparing(m -> (String) m.get("key")));
// 按照Map中的某个key进行降序排序
list.sort(Comparator.comparing(m -> (String) m.get("key")).reversed());
```
其中,`m -> (String) m.get("key")`是一个lambda表达式,用于获取Map中的某个key的值,并返回一个Comparable对象。`Comparator.comparing`方法会使用lambda表达式返回的Comparable对象进行排序,根据返回值进行升序或降序排序。