这是我参与8月更文挑战的第24天,活动详情查看:8月更文挑战
@[TOC](Lambda_09 函数表达式 Stream map) 提取stream中的数据返回。 Stream map 特点
- 通过匿名内部类实现业务或Lambda表达式
- 数据映射转换
- 数据并行计算
代码示例:
public class Lambda10 {
public static void main(String[] args) {
List<Student> list = Arrays.asList(new Student("张三", 18),
new Student("李四", 19),
new Student("王五", 21),
new Student("赵六", 22));
//parallelStream 并行Stream
//转换Stream<List<Student>> ---转换-> Stream<String>
/**
* 通过匿名内部类实现map方法
*/
System.out.println("通过匿名内部类实现map方法");
list.parallelStream().map(new Function<Student, Object>() {
@Override
public Object apply(Student student) {
return student.getName();
}
}).forEach(stu-> System.out.println(stu));
/**
* 通过Lambda表达式实现map方法
*/
System.out.println("====通过Lambda表达式实现map方法");
list.parallelStream().map(t->t.getName()).forEach(stu-> System.out.println(stu));
}
}
class Student {
private String name;
private Integer age;
public Student(String name, Integer age) {
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 +
'}';
}
}
lambda表达式在实际开发中其实很好使用,建议大家多实用lambda表达式,但是就是语法比较抽象,不容易懂。需要多使用才能掌握。
Stream map 特点
- 通过匿名内部类实现业务或Lambda表达式
- 数据映射转换
- 数据并行计算
public class Lambda03 {
public static void main(String[] args) {
/**
* 一个String入参
*/
LambdaInterface31 lambdaInterface31 = (String str) -> System.out.println("welcome:" + str);
lambdaInterface31.fun("Lambda.");
/**
* 两个String入参
*/
LambdaInterface32 lambdaInterface32 = (String name, int age) -> System.out.println(name + "今年" + age + "岁。");
lambdaInterface32.fun("小明", 3);
/**
* 两个int入参 带返回值
*/
LambdaInterface33 lambdaInterface33 = (int x, int y) -> {
int sum = x + y;
return sum;
};
int sum = lambdaInterface33.sum(2, 3);
System.out.println("2+3="+sum);
/**
* 无参数有返回值
*/
LambdaInterface34 lambdaInterface34 = () ->{
System.out.println("无参数有返回值");
return "无参数有返回值";
};
lambdaInterface34.fun();
}
}
interface LambdaInterface31 {
public void fun(String str);
}
interface LambdaInterface32 {
public void fun(String name, int age);
}
interface LambdaInterface33 {
public int sum(int x, int y);
}
interface LambdaInterface34 {
public String fun();
}
输出结果如下:
welcome:Lambda.
welcome:Lambda311.
welcome:Lambda312.