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對象
終止操作則不會返回值,可能不返回值,也可能返回其他類型的單個值

流存在短路運算 如果找到符合的數據就不會判斷其他數據
流相當於一個容器 把所有操作都放進去,然後把數據一個一個的進去操作,而且只有第一個數據所有操作完成後,其他數據才能去操作
分組 group by
分區 partition by

@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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章