技巧:
1.现在有没有一个方法符合我当前的需求
2.如果有这样的方法,这个方法是否满足引用的规则
练习一:
思路:
//集合中的数据还是String类型,要放入Student类型数组中还需要先转型成Student类型
public class MyTest01 {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "张三,23", "李四,24", "王五,25");
Student[] arr = list.stream()
.map(Student::new)
.toArray(Student[]::new);
//打印
System.out.println(Arrays.toString(arr));
//[Student{name = 张三, age = 23}, Student{name = 李四, age = 24}, Student{name = 王五, age = 25}]
}
}
Student类
class Student {
private String name;
private int age;
public Student() {
}
//引用了构造方法,手动满足引用要求
public Student(String str){
this.name=str.split(",")[0];
this.age=Integer.parseInt(str.split(",")[1]);
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//...set get toString
}
练习二:
//只获取姓名可以用map进行类型转换(Student->String)
public class MyTest02 {
public static void main(String[] args) {
ArrayList<Student>list=new ArrayList<>();
Collections.addAll
(list,new Student("张三",23),
new Student("李四",24),
new Student("王五",25));
/*list.stream().map(new Function<Student, String>() {
@Override
public String apply(Student student) {
return student.getName;
}
}).toArray(String[]::new);*/
//使用类名引用方法
String[] arr = list.stream().map(Student::getName).toArray(String[]::new);
System.out.println(Arrays.toString(arr));//[张三, 李四, 王五]
}
}
//使用类名引用方法
Student类:
class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//...set get toString
}
练习三:
思考:
当前有没有一个方法符合我当前的需求,没有就自己写一个
public class Testified {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Collections.addAll
(list,new Student("张三",23),
new Student("李四",24),
new Student("王五",25));
/* //普通写法
list.stream().map(new Function<Student, String >() {
@Override
public String apply(Student student) {
return student.getName()+"-"+student.getAge();
}
}).toArray(String[]::new);
//lambda表达式
String[] arr = list.stream()
.map(student -> student.getName() + "-" + student.getAge())
.toArray(String[]::new);
*/
//方法引用
Student s=new Student();
String[] arr = list.stream().map(Student::print).toArray(String[]::new);
System.out.println(Arrays.toString(arr));
}
}
Student类:
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
//...set get toString
public String print(){
return this.name+"-"+this.age;
}
}