这是我参与8月更文挑战的第25天,活动详情查看:8月更文挑战
- 通过匿名内部类实现业务或lambda表达式
- 多维度(数组)转换数据
- 数据结构层级将维
public class Lambda11 {
public static void main(String[] args) {
List<Integer> listSingle = Arrays.asList(1, 3, 5, 7);
List<Integer> listDouble = Arrays.asList(2, 4, 6, 8);
//将 listSingle listDouble 组装成一个二维数组
System.out.println("打印二维数组数据");
List<List<Integer>> list = Stream.of(listSingle, listDouble).collect(Collectors.toList());
list.forEach((List<Integer> listInt) -> {
listInt.forEach(t -> System.out.print(t));
System.out.println("");
});
//可以简写
System.out.println("===============简写");
list.forEach((listInt) -> listInt.forEach(t -> System.out.print(t)));
/**
* Stream<List<Integer>> ==转换为 ==> Stream<Integer>
* 匿名内部类实现
*/
System.out.println("\n===============匿名内部类实现");
Stream<Integer> stream = list.parallelStream().flatMap(new Function<List<Integer>, Stream<? extends Integer>>() {
@Override
public Stream<? extends Integer> apply(List<Integer> integers) {
return integers.stream();
}
});
stream.forEach(t -> System.out.print(t));
/**
* 使用lambda表达式实现
*/
System.out.println("\n===============lambda表达式实现");
Stream<Integer> streamLambda = list.parallelStream().flatMap((List<Integer> integers) ->{
//Stream<Integer>
return integers.stream();
});
streamLambda.forEach(t -> System.out.print(t));
System.out.println("\n===============lambda表达式实现 简写 ");
Stream<Integer> streamLambdaJX = list.parallelStream().flatMap(t -> t.stream());
streamLambdaJX.forEach(t -> System.out.print(t));
}
}
- 通过匿名内部类实现业务或lambda表达式
- 多维度(数组)转换数据
- 数据结构层级将维
lambda表达式在实际开发中其实很好使用,建议大家多实用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.