java8中使用Lambda表达式将list中实体类的两个字段转Map
昨天一个面试官问我这个问题,当时没回答上来,现在给出代码:
package com.yang.leetcode.temp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* @author: 付东洋 Tel: 13298107421
* @date: 2020/9/22 下午 7:00
* @Decription: 神州信息笔试测试类
**/
public class MainTest {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>() {
{
for (int i = 0; i < 5; i++) {
Student student = new Student();
student.setAge(i);
student.setName(i + "name");
add(student);
}
}
};
Map<Integer, String> collect = list.stream().collect(Collectors.toMap(Student::getAge, Student::getName));
collect.entrySet().forEach(x->{
System.out.println(x.getKey()+x.getValue());
});
}
static class Student {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
}