JDK8新特性02-Stream API

Stream

Stream的創建

	/**
     * 創建Stream幾種方式
     *   1.create from collection.
     *   2.create from values.
     *   3.create from arrays.
     *   4.create from File.
     *   5.create from Iterator.
     *   6.create form Generate.
     */
     
	/**
     * create from collection.
     *
     * @return Stream 
     */
    private static Stream<String> createStreamFromCollection() {
        List<String> list = Arrays.asList("hello", "alex", "alone", "world", "stream");
        return list.stream();
    }

    /**
     * create form values
     *
     * @return Stream
     */
    private static Stream<String> createStreamFromValues() {
        return Stream.of("hello", "alex", "alone", "world", "stream");
    }

    /**
     * create form Arrays
     *
     * @return Stream
     */
    private static Stream<String> createStreamFromArrays() {
        String[] strings = {"hello", "alex", "alone", "world", "stream"};
        return Arrays.stream(strings);
    }

    /**
     * create form File
     *
     * @return Stream
     */
    private static Stream<String> createStreamFromFile() {
        Path path = Paths.get("D:\\Test\\a.txt");
        try (Stream<String> streamFromFile = Files.lines(path)) {
            streamFromFile.forEach(System.out::println);
            return streamFromFile;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * create form Iterator
     *
     * @return Stream
     */
    private static Stream<Integer> createStreamFromIterator() {
        Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(10);
        return stream;
    }
    /**
     * create form Generate
     *
     * @return Stream
     */
    private static Stream<Double> createStreamFromGenerate() {
        return Stream.generate(Math::random).limit(10);
    }

    /**
     * create form Generate
     *
     * @return Stream<Object>
     */
    private static Stream<Obj> createObjStreamFromGenerate() {
        return Stream.generate(new ObjSupplier()).limit(10);
    }

    static class ObjSupplier implements Supplier<Obj> {

        private int index = 0;

        private Random random = new Random(System.currentTimeMillis());

        @Override
        public Obj get() {
            index = random.nextInt(100);
            return new Obj(index, "Name->" + index);
        }
    }

    static class Obj {
        private int id;
        private String name;

        public Obj(int id, String name) {
            this.id = id;
            this.name = name;
        }

        public int getId() {
            return id;
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "Obj{" +
                    "name='" + name + '\'' +
                    ", id=" + id +
                    '}';
        }
    }

Stream的常用方法

Stream Filter

		/**
         *  Stream<T> filter(Predicate<? super T>........ predicate);
         *  過濾
         */
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 6, 7, 7, 1);
        List<Integer> result = list.stream().filter(i -> i % 2 == 0).collect(toList());
        result .forEach(System.out::println);

Stream distinct

        /**
         * Stream<T> distinct();
         * 去重
         */
        result = list.stream().distinct().collect(toList());
        result .forEach(System.out::println);

Stream skip

        /**
         * Stream<T> skip(long n);
         * 跳過
         */
        result = list.stream().skip(50).collect(toList());
        result .forEach(System.out::println);

Stream limit

        /**
         * Stream<T> limit(long maxSize);
         * 同sql中limit一致 , 限制
         */
        result = list.stream().limit(50).collect(toList());
        result .forEach(System.out::println);

Stream map

		/**
         * <R> Stream<R> map(Function<? super T, ? extends R> mapper);
         * 轉map
         */
        result = list.stream().map(i -> i * 2).collect(toList());
        result .forEach(System.out::println);

Stream flatMap

		/**
         * <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
         * 扁平化 例子:將String[] 中重複char去掉
         */
        String[] words = {"Hello", "World"};

        //{h,e,l,l,o},{W,o,r,l,d}
        Stream<String[]> stream = Arrays.stream(words).map(w -> w.split(""));//Stream<String[]>

        //H,e,l,l,o,W,o,r,l,d
        Stream<String> stringStream = stream.flatMap(Arrays::stream);

        stringStream.distinct().forEach(System.out::println);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章