java8的stream中获取listmap中map的key
时间: 2024-02-07 21:41:48 浏览: 27
可以使用Stream的`flatMap`方法将每个Map转换为其键的Stream,然后使用`distinct`方法获取不同的键,最后使用`collect`方法将结果收集到List中。下面是一个示例代码:
```java
List<Map<String, Object>> listMap = ...;
List<String> keys = listMap.stream()
.flatMap(map -> map.keySet().stream())
.distinct()
.collect(Collectors.toList());
```
这样,`keys`列表将包含所有Map中的不同键。
相关问题
java 8 stream List 转 map
可以使用Stream的collect方法将List转换为Map。示例如下:
假设有一个Student类,包含id和name属性:
```
public class Student {
private int id;
private String name;
public Student(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
```
现在有一个List<Student>,需要将其转换为Map<Integer, String>,其中key为Student的id,value为Student的name。
可以使用以下代码实现:
```
List<Student> students = Arrays.asList(
new Student(1, "Alice"),
new Student(2, "Bob"),
new Student(3, "Charlie")
);
Map<Integer, String> studentMap = students.stream()
.collect(Collectors.toMap(Student::getId, Student::getName));
System.out.println(studentMap);
```
输出结果为:
```
{1=Alice, 2=Bob, 3=Charlie}
```
这里使用了Stream的collect方法,其中参数为Collectors.toMap方法,该方法接受两个Function作为参数,第一个Function用于提取Map的key,第二个Function用于提取Map的value。在这个例子中,我们使用Student的getId方法作为key,使用Student的getName方法作为value。
java+stream流list转map
Java 8中使用Stream流将List转换为Map有多种方式,以下是其中两种常见的方式:
1. 使用Collectors.toMap()方法
```java
Map<String, Integer> map = list.stream().collect(Collectors.toMap(obj -> obj.getKey(), obj -> obj.getValue()));
```
其中,list为待转换的List,obj为List中的元素,getKey()和getValue()为获取Map中键值对的方法。
2. 使用Collectors.toMap()方法结合lambda表达式
```java
Map<String, Integer> map = list.stream().collect(Collectors.toMap(obj -> obj.getKey(), obj -> obj.getValue(), (v1, v2) -> v1));
```
其中,list为待转换的List,obj为List中的元素,getKey()和getValue()为获取Map中键值对的方法,v1和v2为value相同时的处理方式,此处为保留v1。