Java8 Stream

来源:互联网 发布:东莞cnc编程培训 编辑:程序博客网 时间:2024/04/28 00:26

1.Stream

Stream是Java 8中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,但是将执行的时间交给具体实现来决定。
Stream与集合的区别:

  1. Stream自己不会存储元素。元素可能被存储在底层的集合中,或者根据需要产生出来;
  2. Stream操作符不会改变源对象。相反,它会返回一个持有结果的新Stream;
  3. Stream操作符可能是延迟执行的。这意味着它们会等到需要结果的时候才会执行。

2.Stream的创建

public class CreateStream {    public static <T> void show(String title, Stream<T> stream){        final int SIZE = 5;        List<T> list = stream.limit(SIZE).collect(Collectors.toList());        System.out.println("title: " + title);        list.forEach(System.out::println);        System.out.println("===============");    }    public static void main(String[] args){        /**         * 1. String stream         */        String str = "Who am I";        Stream<String> strStream = Stream.of(str.split(" "));        show("Context", strStream);        Stream<String> stringStream = Stream.of("ONE", "TOW", "THREE");        show("String", stringStream);        /**         * 2. Array stream         */        String[] arr = {"one", "two", "three"};        Stream<String> arrayStream = Arrays.stream(arr);        show("Array", arrayStream);        Stream<String> arrStream = Arrays.stream(arr, 0, 2);        show("Subarray", arrStream);        /**         * 3. generate infinite stream         */        Stream<String> infiniteStream = Stream.generate(() -> "echo");        show("Infinite", infiniteStream);        Stream<Double> randomStream = Stream.generate(Math::random);        show("Random", randomStream);        Stream<Integer> iterateStream = Stream.iterate(1, n -> n + 1);        show("Iterate", iterateStream);        /**         * 4. regex stream         */        Stream<String> regexStream = Pattern.compile("\\s+").splitAsStream(str);        show("Regex", regexStream);        /**         * 5. IO stream         */        String fileName = "";        try (Stream<String> fileStream = Files.lines(Paths.get(fileName))){            show("File", fileStream);        }        catch (IOException e){            e.printStackTrace();        }        try (BufferedReader reader = Files.newBufferedReader(Paths.get(fileName))){            Stream<String> readerStream = reader.lines();            show("BufferedReader", readerStream);        }        catch (IOException e){            e.printStackTrace();        }        /**         * 6. empty stream         */        Stream<String> emptyStream = Stream.empty();        show("Empty", emptyStream);    }}

3.Stream转换成集合

public class StreamTransCollections {    public static void main(String[] args){        /**         * 1. String         */        Stream<String> stringStream = Stream.of("one", "two", "three", "four", "five");        String str = stringStream.collect(Collectors.joining(", ")).toUpperCase();        /**         * 2. Array         */        Stream<String> arrStream = Stream.of("one", "two", "three", "four", "five");        String[] array = arrStream.toArray(String[]::new);        /**         * 3. List         */        Stream<String> listStream = Stream.of("one", "two", "three", "four", "five");        List<String> list = listStream.collect(Collectors.toList());        Stream<String> arrayListStream = Stream.of("one", "two", "three", "four", "five");        List<String> arrayList = arrayListStream.collect(Collectors.toCollection(ArrayList::new));        /**         * 4. Set         */        Stream<String> setStream = Stream.of("one", "two", "three", "four", "five");        Set<String> set = setStream.collect(Collectors.toSet());        Stream<String> hashSetStream = Stream.of("one", "two", "three", "four", "five");        Set<String> hashSet = hashSetStream.collect(Collectors.toCollection(HashSet::new));        /**         * 5. Stack         */        Stream<String> stackStream = Stream.of("one", "two", "three", "four", "five");        Stack<String> stack = stackStream.collect(Collectors.toCollection(Stack::new));        /**         * 6. Queue         */        Stream<String> queueStream = Stream.of("one", "two", "three", "four", "five");        Queue<String> queue = queueStream.collect(Collectors.toCollection(LinkedList::new));        Stream<String> priorityQueuetream = Stream.of("one", "two", "three", "four", "five");        Queue<String> priorityQueue = priorityQueuetream.collect(Collectors.toCollection(PriorityQueue::new));    }}

4.Stream与基础数据类型

将所有的int收集到Stream<Integer>流中时,需要对每个int值进行装箱,显然是一个低效率的做法。因此,对于Java的八大基础数据类型:int、short、long、float、double、char、byte、boolean,提供了对应的三种Stream:
  • IntSteam:int、short、char、byte、boolean;
  • DoubleStream:float、double;
  • LongStream:long。

5.Stream的操作

把一个数据结构包装成 Stream 后,就要开始对里面的元素进行各类操作了。常见的操作可以归类如下:
  1. Intermediate:map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered;
  2. Terminal:forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator;
  3. Short-circuiting:anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit。

6.Optional类型

Optional<T>对象或者是一个对T类型对象的封装,或者表示不是对象。它比一般指向T类型的引用更加安全,因为它不会返回null。
public class OptionalType {    public static void main(String[] args){        /**         * 1. use optional value         */        String str = "null";        System.out.println(Optional.ofNullable(str).orElse("NULL"));        Optional.ofNullable(str).map(String::length).ifPresent(x -> System.out.println("Length: " + x));        String[] array = {"one", "two", "three", "four"};        Optional<String> optionals = Stream.of(array).filter(x -> x.contains("three")).findAny();        optionals.ifPresent(x -> System.out.println("values: " + x));        Set<String> set = new HashSet<>();        optionals.ifPresent(set::add);        Optional<Boolean> added = optionals.map(set::add);        added.ifPresent(x -> System.out.println("added: " + x));        /**         * 2. create optional value         */        Optional<Double> check = inverse(0d);        check.ifPresent(x -> System.out.println("Check: " + x));        /**         * 3. assembly line operation         */        Optional<Double> ret = Optional.of(4.0).flatMap(OptionalType::inverse).flatMap(OptionalType::squareRoot);        ret.ifPresent(x -> System.out.println("Assembly Line: " + x));    }    public static Optional<Double> inverse(Double x) {        return x == 0 ? Optional.empty() : Optional.of(1 / x);    }    public static Optional<Double> squareRoot(Double x) {        return x < 0 ? Optional.empty() : Optional.of(Math.sqrt(x));    }}




0 0
原创粉丝点击