今天再给出一些代码示例供大家学习lambda学习
package com.vivo.demo.lambda;
import com.vivo.demo.entity.Person;
import com.vivo.demo.entity.User;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
/**
* @author luzaichun
* @date 2019-10-31 19:47
*/
public class Demo1 {
public static void main(String[] args) {
// String s = "my name is AAA";
// List<Integer> collect = Stream.of(s.split(" ")).flatMap(i -> i.chars().boxed()).collect(Collectors.toList());
// collect.stream().forEach(i-> System.out.println((char)i.intValue()));
List<List<String>> list = new ArrayList<>();
List<String> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
list1.add("a");
list1.add("b");
list1.add("c");
list1.add("c");
list2.add("1");
list2.add("2");
list2.add("3");
list.add(list1);
list.add(list2);
//1.收集为list
List<String> collect = list.stream().flatMap(s -> s.stream()).collect(Collectors.toList());
System.out.println("toList收集器:"+collect);
//2.收集为set--去重无序
Set<String> collect2 = list.stream().flatMap(s -> s.stream()).collect(Collectors.toSet());
System.out.println("toSet收集器:"+collect2);
//3.收集为数组
Object[] objects = list.parallelStream().flatMap(s -> s.stream()).toArray();
//4.短路操作findFirst。可用于终止无限流如: new Random().ints().findFirst
Optional<String> optional = list.stream().flatMap(s -> s.stream()).findFirst();
if (optional.isPresent()){
System.out.println("findFirst,拿到第一个值终结流::"+optional.get());
}
//对象list
Person person = new Person();
List<User> userList = new ArrayList<>();
userList.add(new User(1,"zhangsan","123"));
userList.add(new User(2,"lisi","123"));
userList.add(new User(3,"wangwu","123"));
person.setUserList(userList);
//1.获取userList里面每个user的名字
List<String> collect1 = person.getUserList().stream().map(User::getUsername).collect(Collectors.toList());
Optional<String> result = collect1.stream().reduce((s1, s2) -> s1 + "|" + s2);
System.out.println("reduce操作后结果:"+result.get());
//2.reduce操作,可以进行上面的流元素之间的拼接,计算等等。reduce入参是BinaryOperator(两个相同类型入参,返回相同类型一个结果集)
// Optional<Integer> result2 = person.getUserList().stream().map(User::getUserId).reduce((a, b) -> a + b);
Integer reduce = person.getUserList().stream().map(User::getUserId).reduce(0, (a, b) -> a + b);
System.out.println("reduce结果:"+reduce);
}
}
Person对象和User对象我就放一起了,大家看下有哪些属性就好
@Data
public class Person {
private Integer id;
private List<User> userList = new ArrayList<>();
}
@Data
@AllArgsConstructor
public class User {
private Integer userId;
private String username;
private String password;
}
最后我想说一句。学习lambda之间,建议大家学习下函数式接口。大家搞懂这几个函数式接口后,在学习lambda会事半功倍的。例如reduce()入参是BinaryOperator,那么你只要构造出这样一个返回值的函数式就好。