天天看點

java8中Stream的學習

直接上代碼

public class TestStream {
    public static void main(String[] args) {
        TestStream test = new TestStream();
        //test.test0();
        //test.test1();
        //test.test2();
        //test.test3();
        //test.test4();
        //test.test5();
        //test.test6();
        test.test7();
    }

    public void test0(){
        /**
         * 流的建立
         * 1)Collection的預設方法stream()和parallelStream()  parallelStream()與stream()差別是parallelStream()使用多線程去并發周遊,而stream()是單線程
         * 2)Arrays.stream()
         * 3)Stream.of()
         * 4)Stream.iterate()//疊代無限流(1, n->n +1)
         * 5)Stream.generate()//生成無限流(Math::random)
         */

        //1.Collection的預設方法stream()和parallelStream()
        List<String> list = Arrays.asList("a","b","c","d","e","f");
        list.stream();//擷取順序流---單線程操作
        list.stream().map(s -> s.toUpperCase()).forEach(System.out::println);
        list.parallelStream();//多線程操作  但是它不是線程安全的
        list.parallelStream().forEach(System.out::println);//輸出順序不能保證

        //2.Arrays.stream()
        IntStream stream2 = Arrays.stream(new int[]{1, 23, 3, 4, 5, 6});
        Stream<Integer> stream22 = Arrays.stream(new Integer[]{1, 2, 3, 4, 5});

        //3.Stream.of()
        Stream<Integer> stream3 = Stream.of(1, 2, 3, 4, 5, 6);
        IntStream stream33 = IntStream.of(1, 2, 3);

        //4.Stream.iterate()//疊代無限流
        Stream.iterate(1,n -> n+1).limit(10).forEach(System.out::println);

        //5.Stream.generate()//生成無限流
        Stream.generate(Math::random).limit(10).forEach(System.out::println);
    }

    public void test1(){
        /**
         * 流的常用處理
         * 過濾------filter(Predicate<T> p):過濾(根據傳入的Lambda傳回的ture/false 從流中過濾掉某些資料(篩選出某些資料))
         * 去重------distinct():去重(根據流中資料的 hashCode和 equals去除重複元素)
         * 截取------limit(long n):限定保留n個資料
         * 跳過------skip(long n):跳過n個資料
         */
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 3, 4, 3, 6, 7, 8, 9, 11, 14);
        System.out.println("============過濾filter============");
        list1.stream().filter(i->i%2 ==0).forEach(System.out::println);
        System.out.println("============去重distinct============");
        list1.stream().distinct().forEach(System.out::println);
        System.out.println("============截取limit============");
        list1.stream().distinct().limit(3).forEach(System.out::println);
        System.out.println("============跳過skip============");
        list1.stream().distinct().skip(2).forEach(System.out::println);
    }


    public void test2(){
        /**
         * 映射
         * map(Function<T, R> f):接收一個函數作為參數,該函數會被應用到流中的每個元素上,并将其映射成一個新的元素。
         * flatMap(Function<T, Stream<R>> mapper):接收一個函數作為參數,将流中的每個值都換成另一個流,然後把所有流連接配接成一個流
         */
        System.out.println("-------------test1--------------------");
        Stream<String> stream1 = Stream.of("i", "love", "java", "not", "really");
        stream1.map(s -> s.toUpperCase()).forEach(System.out::println);

        Stream<List<String>> stream2 = Stream.of(Arrays.asList("H","E"),Arrays.asList("L","L","O"));
        stream2.flatMap(list -> list.stream()).forEach(System.out::println);
    }

    public void test3(){
        /**
         * 排序
         * sorted():自然排序使用Comparable<T>的int compareTo(T o)方法
         * sorted(Comparator<T> com):定制排序使用Comparator的int compare(T o1, T o2)方法
         * 統計
         * count():傳回流中元素的總個數
         * max(Comparator<T>):傳回流中最大值
         * min(Comparator<T>):傳回流中最小值
         */
        System.out.println("============自然排序============");
        List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5, 3, 4, 3, 6, 7, 8, 9, 11, 14);
        list1.stream().sorted().forEach(System.out::println);
        System.out.println("============自定義排序============");
        list1.stream().sorted((x,y) -> y.compareTo(x)).forEach(System.out::println);
        System.out.println("============總數============");
        System.out.println(list1.stream().count());
        System.out.println("============最大值和最小值============");
        System.out.println(list1.stream().max((x,y)->x.compareTo(y)).get());
        System.out.println(list1.stream().min((x,y)->x.compareTo(y)).get());
    }

    public void test4(){
        /**
         * 收集流  查找比對
         * allMatch:檢查是否比對所有元素
         * anyMatch:檢查是否至少比對一個元素
         * noneMatch:檢查是否沒有比對的元素
         * findFirst:傳回第一個元素(傳回值為Optional<T>)
         * findAny:傳回目前流中的任意元素(一般用于并行流)
         */
        System.out.println("======================檢查是否比對所有==========================");
        List<Integer> list1 = Arrays.asList(2, 3, 4, 5, 3, 4, 3, 6, 7, 8, 9, 11, 14);
        System.out.println(list1.stream().allMatch(x -> x > 0));
        System.out.println("======================檢查是否至少比對一個元素==========================");
        System.out.println(list1.stream().anyMatch(x -> x>9));
        System.out.println("======================檢查是否沒有比對的元素==========================");
        System.out.println(list1.stream().noneMatch(x -> x>9));
        System.out.println(list1.stream().noneMatch(x -> x>19));
        System.out.println("======================傳回第一個元素==========================");
        System.out.println(list1.stream().findFirst().get());
        System.out.println("======================傳回目前流中的任意元素==========================");
        Optional<Integer> any = list1.stream().findAny();
        System.out.println(any.get());
    }

    public void test5(){
        /**
         * 歸約
         * reduce(T identity, BinaryOperator) / reduce(BinaryOperator) :将流中元素挨個結合起來,得到一個值。
         */
        System.out.println("===============reduce:将流中的元素反複結合起來,得到一個值===============");
        System.out.println(Stream.iterate(1,x->x+1).limit(100).reduce(0,(x,y)->x+y));
        System.out.println(Stream.iterate(1,x->x+1).limit(10).reduce(1,(x,y)->x*y));
    }

    public void test6(){
        /**
         * 彙總
         * collect(Collector<T, A, R>):将流轉換為其他形式。
         * collect:将流轉換為其他形式:list
         * collect:将流轉換為其他形式:set
         * collect:将流轉換為其他形式:TreeSet
         * collect:将流轉換為其他形式:map
         * collect:将流轉換為其他形式:sum
         * collect:将流轉換為其他形式:avg
         * collect:将流轉換為其他形式:max
         * collect:将流轉換為其他形式:min
         */
        System.out.println("=====collect:将流轉換為其他形式:list");
        Stream.of(1,2,3,4,5,6,7,8,9).collect(Collectors.toList()).forEach(System.out::println);
        System.out.println("=====collect:将流轉換為其他形式:set");
        Stream.iterate(1,x->x+1).limit(10).collect(Collectors.toSet()).forEach(System.out::println);
        System.out.println("=====collect:将流轉換為其他形式:TreeSet");
        Stream.generate(Math::random).limit(5).collect(Collectors.toCollection(TreeSet::new)).forEach(System.out::println);
        System.out.println("=====collect:将流轉換為其他形式:map");//相當于第一個是key第二個是value一次類推如果數量不夠會報錯!
        Map<Integer, String> stringMap = Arrays.asList(3, 4, 5, 2, 2, 3, 4, 5, 6, 7, 8, 8, 9,10,11).stream().distinct().collect(Collectors.toMap(Integer::intValue, integer -> integer + 10 + ""));
        Iterator<Integer> iterator = stringMap.keySet().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            System.out.println(stringMap.get(iterator.next()));
        }
        System.out.println("=====collect:将流轉換為其他形式:sum");
        Integer sum = Arrays.asList(3, 2, 5, 6, 7, 8, 9, 4, 3, 1, 2, 4).parallelStream().collect(Collectors.summingInt(Integer::intValue));
        System.out.println(sum);
        System.out.println("=====collect:将流轉換為其他形式:avg");
        System.out.println(Stream.iterate(1,x->x+1).limit(100).collect(Collectors.averagingInt(Integer::intValue)));
        System.out.println("=====collect:将流轉換為其他形式:max");
        List<Double> list = Stream.generate(Math::random).limit(10).sorted((x,y) -> x.compareTo(y)).collect(Collectors.toList());
        list.forEach(System.out::println);
        Optional<Double> max = list.stream().collect(Collectors.maxBy(Double::compareTo));
        System.out.println(max.get());
        System.out.println("=====collect:将流轉換為其他形式:min");
        System.out.println(Stream.iterate(1,x -> x+1).limit(100).collect(Collectors.minBy((x,y) -> x.compareTo(y))).get());
    }

    public void test7(){
        /**
         * 分組和分區
         * Collectors.groupingBy()對元素做group操作。
         * Collectors.partitioningBy()對元素進行二分區操作
         */
        List<Product> lists = Arrays.asList(new Product(1,"蘋果電腦",5888.88,"電腦"),
                                            new Product(2,"ASUS垃圾電腦",6899.33,"電腦"),
                                            new Product(3,"聯想筆記本(也一般)",9899.33,"電腦"),
                                            new Product(4,"機械鍵盤",499.33,"鍵盤"),
                                            new Product(5,"雷蛇滑鼠",222.22,"滑鼠"),
                                            new Product(6,"iphone XR",4088.00,"手機"),
                                            new Product(7,"HUAWEI Mate 20 RS",15888.00,"手機"));
        //1.根據商品分類名稱進行分組
        //2.根據商品價格範圍多級分組
        //3.根據商品價格是否大于1000進行分區
        System.out.println("====================根據商品分類名稱進行分組=====================");
        Map<String, List<Product>> map = lists.stream().collect(Collectors.groupingBy(Product::getDirName));
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        System.out.println("====================根據商品價格範圍多級分組=====================");
        Map<Double, Map<String, List<Product>>> map1 = lists.stream().collect(Collectors.groupingBy(Product::getPrice, Collectors.groupingBy(p -> {
            if (p.getPrice() > 1000) {
                return "進階貨";
            }else {
                return "便宜貨";
            }
        })));
        System.out.println(map1);
        System.out.println("====================根據商品價格是否大于1000進行分區=====================");
        Map<Boolean, List<Product>> listMap = lists.stream().collect(Collectors.partitioningBy(p -> p.getPrice() > 1000));
        System.out.println(listMap);

    }

}

@Accessors(chain = true)
@Data
class Product{
    public int id;
    public String name;
    public double price;
    public String dirName;

    public Product(int id, String name, double price, String dirName) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.dirName = dirName;
    }
}
           

繼續閱讀