java8-Stream 流 API

A review and explanation

After release of the previous three chapters java8 blog, you will understand why we use the Lamda expression, and the relationship between the principle of Lamda expression of functional interface reference from Lamda expressions to reference methods and constructors.

Stream flow you want to learn to be familiar to previous knowledge and grasp, today we are speaking about advanced Lamda expression of learning, Stream stream API.

What are the two streams Stream

Flow like more than we all know, such as food packaging process, you have to have a food staff to provide food, processed food processing, add spices, ..., packaging and assembly. Simply put, ordinary streams like factory assembly line the same.

Stream flow can be can be used to declaratively set of operations (operating sql database can imagine that), it can be seen through the data set of high-level iterators . When the operation flow we can be likened to the factory assembly line.

Three advantages flow

What are the advantages of it flow? Flow turned out to be an iterative, a cycle that it and for the collection of any difference, why do we use iterative flow to it?

  • Data collection is stored computed, we use a set of traversal, must stay the course, we can not be interrupted. Stream flow like a stream as we can load the first part, see part can pause interrupted halfway leave; the set flow compared to the more flexible
  • Iterating flow is disposable, which means you can only iteration once a stream, complete iteration of this flow was consumed.
  • Compared to the stream for the internal loop iteration, as long as we give a specific operational flow will function ok, but for external loop iteration.

During operation four Stream stream

Stream flow line with the flow-based formula with a supply source of the operation, the process terminates three
Here Insert Picture Description
common intermediate operational flow:
Here Insert Picture Description
Common End Flow:
Here Insert Picture Description

Five common StreamAPI

Initialization vehicle information

    public List<Car> InitCar(){
        ArrayList<Car> carList = new ArrayList<>();
        Car car1 = new Car("100", "black", "中国", 20);
        Car car2 = new Car("101", "gray", "中国", 30);
        Car car3 = new Car("102", "yello", "中国", 50);
        Car car4 = new Car("103", "silvery", "英国", 20);
        Car car5 = new Car("104", "red", "英国", 30);
        carList.add(car1);
        carList.add(car2);
        carList.add(car3);
        carList.add(car4);
        carList.add(car5);
        return carList;
    }

Filter

The filter function is to filter out the elementary stream, we need - intermediate operation

    @Test
    public void filterTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 筛选车辆时黑色的车
        List<Car> result = cars.stream()
                .filter(car -> car.getColor().equals("black"))
                .collect(Collectors.toList());
        //[Car(code=100, color=black, factory=中国, price=20.0)]
        System.out.println(result);

    }

Sort 2

sorted in ascending order elements will default function - to manipulate the intermediate

   @Test
    public void sortTest(){
        int[] ints = {0, 5, 7, 6, 15, 13, 27};
        Arrays.stream(ints).sorted().forEach(System.out::println);
    }

3 deduplication

remove duplicate distinct elements - intermediate operation

    @Test
    public void distinctTest(){
        int[] ints = {5,6,5,6,27};
        // 5 6 27
        Arrays.stream(ints).distinct().forEach(System.out::println);
    }

4 cut

Limit function limits the flow element - intermediate operation

   @Test
    public void limitTest(){
        int[] ints = {5,6,5,6,27};
        // 5 6 
        Arrays.stream(ints).limit(2).forEach(System.out::println);
    }

5 jump

skip skip function n elements - intermediate operating

    @Test
    public void skipTest(){
        int[] ints = {5,6,5,6,27};
        // 27
        Arrays.stream(ints).skip(4).forEach(System.out::println);
    }

6 Mapping

is a map conversion function, a function accepts as a parameter, which is mapped on each element, transition to the new element. - intermediate operation

    @Test
    public void mapTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 只获得车的价格
        cars.stream().limit(1)
                .map(Car::getPrice)
                .forEach(System.out::println);//20.0
    }

7 flattened stream

SUMMARY flatMap intermediate can function as a plurality of streams of the combined stream. - intermediate operation

    @Test
    public void flatMapTest(){
        String[] array = {"youku1327"};
        // 存放的是一个个数组 [Ljava.lang.String;@61f3fbb8
        Arrays.stream(array).map(s -> s.split(""))
                .forEach(System.out::print);
        // 将一个个数组流合并为一个流输出:youku1327
        Arrays.stream(array).map(s -> s.split(""))
                .flatMap(Arrays::stream)
                .forEach(System.out::print);
    }

8 Any match

anyMatch function matched to an element of any flow returns true. --- operation is terminated

    @Test
    public void anyMatchTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 任意匹配黄色的车
        boolean yello = cars.stream()
                .anyMatch(car -> car.getColor().equals("yello"));
        System.out.println(yello);//true
    }

9 exact match

allMatch exact match element stream function returns true. - termination of operations

   @Test
    public void allMatchTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 完全匹配黄色的车
        boolean yello = cars.stream()
                .allMatch(car -> car.getColor().equals("yello"));
        System.out.println(yello);//false
    }

10 non-matching

noneMatch function does not match any of the elements to flow returns true. ------ terminate operation

    @Test
    public void noneMatchTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 不是youku1327这个颜色的车
        boolean yello = cars.stream()
                .noneMatch(car -> car.getColor().equals("youku1327"));
        System.out.println(yello);//true
    }

11 seeking an arbitrary element stream

findAny find a function of any element of the returned stream. --- operation is terminated

    @Test
    public void findAnyTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 不是youku1327这个颜色的车
        Optional<Car> anyCar = cars.stream().findAny();
        Car car = anyCar.orElse(new Car("141", 50));
        // Car(code=100, color=black, factory=中国, price=20.0)
        System.out.println(car);
    }

12 looking for the first element in stream

findFirst function searches the first elementary stream. -------- terminate operation

    @Test
    public void findFirstTest(){
        // 初始化车辆
        List<Car> cars = carFunFactory.InitCar();
        // 不是youku1327这个颜色的车
        Optional<Car> anyCar = cars.stream().findFirst();
        // Car(code=100, color=black, factory=中国, price=20.0)
        System.out.println(anyCar.get());
    }

13 reduction

After reduce function parameter into a front and a reference value after the operation as a reference before the first operation of the next, and so on. - termination of operations

    @Test
    public void reduceTest(){
        int[] ints = {3,4,5,};
        int reduce = Arrays.stream(ints)
                .reduce(0, (left, right) -> left + right);
        // 求和 12
        System.out.println(reduce);
        OptionalInt max = Arrays.stream(ints).reduce(Integer::max);
        // 求最大值 5
        System.out.println(max.getAsInt());
        OptionalInt min = Arrays.stream(ints).reduce(Integer::min);
        // 求最小值 3
        System.out.println(min.getAsInt());
    }

14 NUMERICAL

IntStream, DoubleStream and LongStream, respectively flow into the element Laid int, long and double, avoiding automatic packing
. ----- intermediate operation

    @Test
    public void numTest(){
        int[] ints = {5,6,5,6};
        // int流
        IntStream intStream = Arrays.stream(ints);
        // 6767爱看youku1327
        intStream.mapToObj(value -> value+1).forEach(System.out::print);
        System.out.println("爱看youku1327");
        double[] doubles = {5,6,5,6};
        // double流
        DoubleStream doubleStream = Arrays.stream(doubles);
        //5.06.05.06.0关注youku1327
        doubleStream.forEach(System.out::print);
        System.out.println("关注youku1327");
        // long流
        Long[] longs = {5L,6L,5L,6L};
        Stream<Long> longStream = Arrays.stream(longs);
        long count = longStream.count();
        // 4
        System.out.println(count);

    }

15 stream conversion

boxed transfer function values ​​as the original stream. ----- intermediate operation

    @Test
    public void streamSwapTest(){
        int[] ints = {5,6,7};
        // 将int流转为原始流
        Optional<Integer> first = Arrays.stream(ints).boxed().findFirst();
        System.out.println(first.get());//5
        // 2.23606797749979  2.449489742783178 2.6457513110645907
        Arrays.stream(ints).boxed()
                .mapToDouble(s ->Math.sqrt(s))
                .forEach(System.out::println);
    }

Six Building Streams

Generating a flow value

    @Test
    public void buildStreamByValue(){
        Stream<String> stream = Stream.of("关", "注", "微", "信", "公", "众", "号", ":", "youku1327", "谢谢");
        //关注微信公众号:youku1327谢谢
        stream.map(StringUtils::join).forEach(System.out::print);
    }

2 Created by an array of stream

 @Test
    public void skipTest(){
        int[] ints = {5,6,5,6,27};
        // 27
        Arrays.stream(ints).skip(4).forEach(System.out::println);
    }

3 Create a file stream

    @Test
    public void buildStreamByFile(){
        try {
            Stream<String> lines = Files.lines(Paths.get("C:\\mydata\\youku1327.txt"), Charset.defaultCharset());
            lines.map(s -> s.split(""))
                    .flatMap(Arrays::stream)
                    .forEach(System.out::print);//youku1327
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

4 Create an unlimited stream

generate and iterate is to create an unlimited flow, we have to look at the constraints, so wireless stream has been created elements.

    @Test
    public void buildStreamByIterate(){
        long count = Stream.iterate(1, integer -> integer + 1)
                .limit(100)
                .count();
        System.out.println(count);//100
    }

Seven Acknowledgments

After watching this one stream streaming API operations basically you can do many ordinary scenes work, senior operations will continue to update the back flow of
the final push wave of public micro-channel number, are interested in learning on the attention to it.

Here Insert Picture Description

Guess you like

Origin www.cnblogs.com/zszxz/p/12066889.html