java stream api常用操作

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lovelovelovelovelo/article/details/88181300

collect(toList())

由stream里的值生成一个列表
stream的of操作使用一组初始值生成新的stream

List<String> collected = Stream.of("a","b","c").collect(Collectors.toList());
collected.stream().forEach(c -> System.out.println(c));	

map

将一个流中的值转换为一个新的流

List<String> collected = Stream.of("hello","java","stream").map(s -> s.toUpperCase()).collect(Collectors.toList());
collected.stream().forEach(c -> System.out.println(c));	

在这里插入图片描述

filter

遍历数据并检查其中的元素

List<String> collected = Stream.of("hello","java","stream").filter(s -> s.startsWith("j")).collect(Collectors.toList());
collected.stream().forEach(c -> System.out.println(c));

在这里插入图片描述

flatmap

flatmap可用stream替换值,然后将多个stream连接成一个stream

List<Integer> collected = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)).flatMap(numbers -> numbers.stream()).collect(Collectors.toList());
collected.stream().forEach(c -> System.out.println(c));	

max和min

public static void main(String[] args) {
	Student s1 = new Student("tom", 12);
	Student s2 = new Student("tom", 15);
	Student s3 = new Student("tom", 8);
	List<Student> students = Arrays.asList(s1,s2,s3);
	Student youngest = students.stream().min(Comparator.comparing(student -> student.getAge())).get();
	System.out.println(youngest);
}

输出:name:tom,age:8

min和max方法返回Optional对象

reduce

reduce操作可以实现从一组值中生成一个值

实现求和操作

int count = Stream.of(1,2,3).reduce(0, (a,b) -> a+b);

猜你喜欢

转载自blog.csdn.net/lovelovelovelovelo/article/details/88181300