java 8 list转成map stream
时间: 2023-11-18 07:57:36 浏览: 61
在Java 8中,我们可以使用stream和Lambda表达式来实现List转Map的需求。具体实现方法如下:
```java
List<Person> personList = new ArrayList<>();
personList.add(new Person("Tom", 20));
personList.add(new Person("Jerry", 22));
personList.add(new Person("Mike", 25));
Map<String, Integer> personMap = personList.stream()
.collect(Collectors.toMap(Person::getName, Person::getAge));
```
上述代码中,我们首先创建了一个Person类的List,然后使用stream()方法将其转换为Stream流。接着,使用collect()方法将Stream流转换为Map集合,其中Person::getName表示将Person对象的name属性作为Map的key,Person::getAge表示将Person对象的age属性作为Map的value。
需要注意的是,如果List中存在重复的key值,那么在转换为Map时会抛出IllegalStateException异常。可以通过使用toMap()方法的第三个参数来指定当key值重复时的处理方式。
相关问题
java stream将list转换成map
Java 8引入了一个Stream API,它提供了一种简洁的方式来处理集合。我们可以使用Stream API将List转换成Map。下面是一个示例代码:
```
List<Person> personList = new ArrayList<>();
personList.add(new Person(1, "Alice"));
personList.add(new Person(2, "Bob"));
personList.add(new Person(3, "Charlie"));
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
System.out.println(personMap);
```
在上面的代码中,我们首先创建了一个Person对象列表。然后使用Stream API的collect方法将其转换为Map。在collect方法中,我们使用了toMap方法,它接受两个参数,一个是Key的映射函数,另一个是Value的映射函数。在这个例子中,我们使用Person对象的id作为Key,使用Person对象的name作为Value。
如果要将List转换为Map并且Key有重复的情况,可以使用toMap方法的第三个参数来指定Key重复时的处理方式。
java8 List转成map
可以使用Java 8中的stream API和collectors类将List转换为Map。
假设有一个Person类,具有id和name属性:
```
public 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;
}
}
```
现在有一个List<Person>,想将其转换为Map<Integer, String>,其中键是id,值是name。可以使用以下代码:
```
List<Person> personList = new ArrayList<>();
personList.add(new Person(1, "Alice"));
personList.add(new Person(2, "Bob"));
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(Person::getId, Person::getName));
```
在这里,使用stream()方法将List转换为流,然后使用collect()方法将其收集到Map中。toMap()方法需要两个参数,第一个参数用于指定键的函数,第二个参数用于指定值的函数。在这里我们使用Person::getId作为键函数,Person::getName作为值函数。
如果Person类没有实现getId()和getName()方法,可以使用lambda表达式提供相应的实现:
```
Map<Integer, String> personMap = personList.stream()
.collect(Collectors.toMap(p -> p.getId(), p -> p.getName()));
```