Java8 stream流的一些感悟

流 分中间操作 终止操作 如果没有终止操作 中间操作不执行
Collectors.joining("/")
flatMap() 将所有的流打平了 打成一个流
Stream<List> stream = Stream.of(Arrays.asList(1),Arrays.asList(2,3),Arrays.asList(4,5,6));
stream.flatMap(list->list.stream()).map(item->item*item).forEach(System.out::println);
集合关注的是数据与数据存储本身
流关注的是对数据的计算
流是无法重复使用的

中间操作都会返回stream对象
终止操作则不会返回值,可能不返回值,也可能返回其他类型的单个值

流存在短路运算 如果找到符合的数据就不会判断其他数据
流相当于一个容器 把所有操作都放进去,然后把数据一个一个的进去操作,而且只有第一个数据所有操作完成后,其他数据才能去操作

@Test
    public void test1(){
        List<String> list = Arrays.asList("hello","world","hello world");
        list.stream().mapToInt(item->{
            int length =item.length();
            System.out.println(item);
            return length;
        }).filter(item->item==5).findFirst().ifPresent(System.out::println);

        List<String> list1 = Arrays.asList("hello world","hello welcome","welcome world");
        List<String> list2 = list1.stream().map(item->item.split(" ")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
        list2.forEach(System.out::println);
    }

打印出来的数据

hello//找到符合条件的hello 就不会去找后面的数据
5
---------------------
hello
world
welcome
发布了80 篇原创文章 · 获赞 140 · 访问量 64万+

猜你喜欢

转载自blog.csdn.net/linjpg/article/details/104228402