Stream流创建
Collection接口的stream()方法
ArrayList<String> list = Lists.newArrayList("thor", "loki", "stark");
Stream<String> stream1 = list.stream();
Stream接口的of方法创建
Stream<String> stream2 = Stream.of("thor", "loki", "stark");
map操作
需要传入一个Function函数式接口的匿名对象,实现对流中数据的操作
小写转大写
List<String> newList1 = stream1.map(str -> str.toUpperCase()).collect(Collectors.toList());
filter操作
需要传入一个Preedicate函数式接口的匿名对象,实现流中数据的过滤
过滤年龄小于20的学生
private static void filterAgeLessThan20() {
Stream<Student> studentStream = Stream.of(new Student(1, "小明", 20),
new Student(2, "小张", 22), new Student(3, "小陈", 23));
List<Student> filterList = studentStream.filter(student -> student.getAge() > 20).collect(Collectors.toList());
System.out.println(filterList);
}
peek操作
需要传入一个Consumer函数式接口的匿名对象,可以在流操作过程中进行打印测试
Stream<Student> studentStream = Stream.of(new Student(1, "小明", 20),
new Student(2, "小张", 22), new Student(3, "小陈", 23));
// count计算流中数据个数
long count = studentStream.filter(student -> student.getAge() > 20).peek(System.out::println).count();
reduce操作
- 需要传入BiFunction函数式接口
- 假设需要获取上面操作中全部学生的年龄,使用reduce操作如下:
private static void stuAgeSum() {
Stream<Student> studentStream = Stream.of(new Student(1, "小明", 20),
new Student(2, "小张", 22), new Student(3, "小陈", 23));
Optional<Integer> optional = studentStream.map(student -> student.getAge()).reduce((age1, age2) -> age1 + age2);
if (optional.isPresent())
System.out.printf("学生的年龄总和:%d",optional.get());
}
max | min | count
计算流中最大 | 最小 | 数量
Stream<Student> studentStream = Stream.of(new Student(1, "小明", 20),
new Student(2, "小张", 22), new Student(3, "小陈", 23));
Optional<Student> max = studentStream.max((stu1, stu2) -> stu1.getAge() - stu2.getAge());
map转list
private static void mapToList() {
Map<String,Object> stuMap = new HashMap<>();
stuMap.put("1",new Student(1,"小张",22));
stuMap.put("2",new Student(2,"小杨",20));
List<Object> stuList = stuMap.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());
System.out.println(stuList);
}
list转map
private static void listToMap() {
Stream<Student> studentStream = Stream.of(new Student(1, "小明", 20),
new Student(2, "小张", 22), new Student(3, "小陈", 23));
Map<Integer, String> stuMap = studentStream.collect(Collectors.toMap(Student::getId, Student::getUsername));
System.out.println(stuMap);
}