public class Student {
private String name;
private Integer age;
public Student() {
super();
}
public Student(String name, Integer age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + "]";
}
}
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DemoJdk {
public static void main(String[] args) {
Student stu = new Student("kxs",15);
Student stu1 = new Student("kxs1",18);
Student stu2 = new Student("kxs2",19);
List<Student> lists = Arrays.asList(stu,stu1,stu2); //把对象添加到集合中,可以使用集合的add()方法,
List<String> listNames = lists.stream().map(Student::getName).collect(Collectors.toList());
System.out.println("名字集合listNames"+listNames);//名字集合listNames[kxs, kxs1, kxs2]
List<String> listName2 = lists.stream().map(entity->entity.getName()).collect(Collectors.toList());
System.out.println("名字集合listName2"+listName2);//名字集合listName2[kxs, kxs1, kxs2]
List<String> listName3 = lists.stream().map(entity->{
return entity.getName();//在idea里面可能会报错,因为如果{}里面就一行代码{}和return可以省略
}).collect(Collectors.toList());
System.out.println("名字集合listName3"+listName3);//名字集合listName3[kxs, kxs1, kxs2]
}
}