java8(2)--- Stream API

1. Briefly

In Java8 have two of the most important changes. The first is a Lambda expression; the other is the Stream API.

Stream processing is a collection of abstract concept, it can specify that you want a set of operations performed, can perform very complex search, filtering and mapping data and other operations. Use Stream API to manipulate the data collection, similar to using a SQL database query execution, such as grouping operation can achieve the group by. Anyway efficient introduction of Stream API provides data processing.

 

What flow (Stream) that? Rheological blood through the blood vessels of the heart the whole body, when in the blood vessels can be seen as a stream, fell ill and needed infusion through the blood vessels, that were operating in this stream. Heart blood can be considered as a data set, converted into a transport stream through a blood vessel, this operation is equivalent to an infusion operation is made to our Stream API, i.e. for the flow calculation process.

Is a collection of data stream is calculated.

 

have to be aware of is:

  1.Stream it will not store element.

  2.Stream does not change the source object. Instead, they will return the result of holding a new Stream.

  3.Stream operations are delayed execution. This means they will need to wait until the results have to be performed.

Stream three steps:

  1. Create stream

  2. Operation Flow

  3. terminate the operation to obtain the results, attention: after flow termination operation can not be used again

2.API in Action

  2.1. Creating Flow

        // set creating flow 
        Stream <Student> STREAM1 = studentList.stream (); 

        // Stream static methods for creating flow 
        Stream <Student> STREAM2 = Stream.of (
                 new new Student (. 1, "Joe Smith", 12 is, 69 ),
                 new new Student (2, "John Doe", 12 is, 78.5 ),
                 new new Student (. 3, "Wang Wu", 13 is, 95 ),
                 new new Student (. 4, "Zhao six", 14, 23 is ),
                 new new Student (. 5, " Sun seven ", 11, 55.5 ) 
        ); 
        // array creation stream 
        stream <Student> = Arrays.stream stream ( new new Student [] {});

  2.2. Operation Flow

    2.2.1 Screening and segmentation

      filter (Predicate p) receiving Lambda, exclude certain elements from the stream.

      DISTINCT () filter, the flow generated by the elements hashCode () and equals () deduplication element, rewriting remember

      limit (long maxSize) cut off the flow, so that the element does not exceed a given number. limit values ​​found qualified will not continue to the end to find all

      skip (long n) skipped element, a return flow throw the first n elements. If the flow is less than n number of elements, an empty stream. And the limit (n) of complementary

        // filter filtration older than 12 
        studentList.stream () 
                .filter (Student -> student.getAge ()> 12 ) 
                .forEach (System.out :: println); 
        System.out.println ( "----- --------- " ); 

        // DISTINCT to heavy 
        studentList.stream () 
                .distinct () 
                .forEach (System.out :: println); 
        System.out.println ( " ------ -------- " ); 

        // after filtration to take the first two, somewhat similar to the limit mysql's,
         // limit values found qualified will not continue to look for the end of all, the following statement will only output performed twice, because the first two conditions is satisfied 
        studentList.stream () 
                .filter ((Student) -> {
                        System.out.println ( "performs filtering" );
                         return student.getAge ()> = 12 is ; 
                }) 
                .limit ( 2 ) 
                .forEach (the System.out :: the println); 
        System.out.println ( "--- ----------- " ); 

        // skip skip satisfy two conditions before 
        studentList.stream () 
                .filter (Student -> student.getAge ()> = 12 is ) 
                .skip ( 2 ) 
                . forEach (System.out :: println);

    2.2.2 Mapping

      map (Function f) receiving a function as a parameter, the function will be applied to each element, and maps it into a new element

      flatMap (Function f) receiving a function as a parameter, the value of each stream are replaced with another stream, then all flows connected into one stream

      Somewhat similar to the list and add the addAll method, a single element is added to the collection, a one by one is added to another set of elements in the set

    public  void testStream2 () { 

        // the function map is applied to each element, generates a new element, that is, the name of each student is collected to form a new element 
        studentList.stream () 
                .distinct () 
                .map (Student -> student.getName ()) 
                .forEach (System.out :: println); 
        System.out.println ( "--------" );
         // call the method creatStream each Student object is converted into a stream, and then each stream flatMap aggregated into a stream 
        studentList.stream () 
                .distinct () 
                .flatMap (StreamTest :: creatStream) 
                .forEach (the System.out :: the println); 
    } 
    public  static stream <Student> creatStream(Student student){
        return Stream.of(student);
    }

    2.2.3 Sorting

      sorted () generates a new stream, wherein the natural order sort

      sorted (Comparator comp) generates a new stream, wherein the comparator sorted order

  2.3 Flow obtain results

    2.3.1 Find and match 

      allMatch (Predicate p) to check whether all the elements match

      anyMatch (Predicate p) to check whether the elements match at least one

      noneMatch (Predicate p) to check whether all the elements do not match

      the findFirst () returns the first element in the operation flow (the encapsulated Optional)

      findAny () returns any element (Optional encapsulated in) current flow, parallel flow results randomness

      count () Returns the total number of elements in the flow

      max (Comparator c) Returns the maximum flow (the encapsulated Optional)

      min (Comparator c) returns the minimum value in the stream (in the encapsulated Optional)

      forEach (Consumer c) internal iteration

     // allMatch (the Predicate P) to check whether all elements of all matches Age Student> 12 is 
        Boolean Result = studentList.stream () 
                .allMatch (Student -> student.getAge ()> 12 is ); 
        System.out.println (Result); 

        // AnyMatch (the Predicate P) to check whether the elements match at least one 
        Result = studentList.stream () 
                .anyMatch (Student -> student.getAge () == 12 is ); 
        System.out.println (Result); 

        // noneMatch (the Predicate p) check if there is no match all elements 
        Result = studentList.stream () 
                .noneMatch (Student -> student.getAge () <. 11 ); 
        System.out.println (Result);
        // the findFirst () returns the first element in the operation flow (the encapsulated Optional)
         // taken after the first score by ascending 
        Student Student = studentList.stream () 
                .sorted ((student1, STUDENT2) -> Double .compare (student1.getScore (), student2.getScore ())) 
                .findFirst () 
                .get (); 
        System.out.println (Student); 

        Student = studentList.stream () 
                .findAny () 
                .get (); 
        System.out.println (student);

    2.3.2 Reduction

      reduce (T iden, BinaryOperator b) may be repeated to combine stream elements, to obtain a value. Return T

      reduce (BinaryOperator b) may be repeated to combine stream elements, to obtain a value. Back Optional <T>

      Connection map and reduce map-reduce commonly referred to as Mode

        // accumulated, the flow summing elements 
        List <Integer> Arrays.asList List = (1,2,3,4,5,6,7,8,9,10 ); 
        Integer SUM = list.stream () 
                .reduce ( 0, (X, Y) -> X + Y); 
        System.out.println (SUM); 

        // find out the student 
        Double allScore = studentList.stream () 
                .map (student -> student.getScore ()) 
                .reduce (Double :: SUM) 
                .get (); 
        System.out.println (allScore);

    2.3.3 collection     

      collect (Collector c) the stream is converted to other forms. Receiver (collector) of a Collector implemented interfaces, methods to make Stream Summary for elements

      Collector implement the interface method determines how convection do the collection (such as collecting the List, Set, Map).

      Collectors 1.8 provides tools to create common collector instance easily

Collectors

 

 

        List<Student> studentList = Arrays.asList(
                new Student(1, "张三", 12, 69, Student.Clazz.Clazz2),
                new Student(2, "李四", 12, 78.5,Student.Clazz.Clazz2),
                new Student(3, "王五", 13, 95, Student.Clazz.Clazz3),
                new Student(4, "赵六", 14, 23, Student.Clazz.Clazz3),
                new Student(5, "孙七", 11, 55.5, Student.Clazz.Clazz1),
                new Student(5, "孙七", 11, 55.5, Student.Clazz.Clazz1)
        );

        //toList() 收集到List集合中
        List<String> nameList = studentList.stream()
                .map(student -> student.getName())
                .collect(Collectors.toList());
        System.out.println(nameList);
        //toSet() 收集到Set集合中 自动去重 默认返回的HashSet
        Set<String> nameSet= studentList.stream()
                .map(student -> student.getName())
                .collect(Collectors.toSet());
        System.out.println(nameSet);
        System.out.println(nameSet.getClass());
        //返回指定集合类型
        TreeSet<String> nameTreeSet= studentList.stream()
                .map(student -> student.getName())
                .collect(Collectors.toCollection(TreeSet::new));
        System.out.println(nameTreeSet.getClass());

        //分组groupingBy 返回map集合 类似sql group by了
        //根据年级分组
        Map<Student.Clazz, List<Student>> map = studentList.stream()
                .collect(Collectors.groupingBy(Student::getClazz));
        System.out.println(map);
        //多次分组
        //先按年级再按年龄
        Map<Student.Clazz, Map<Integer, List<Student>>> map2 = studentList.stream()
                .collect(Collectors.groupingBy(Student::getClazz, Collectors.groupingBy(Student::getAge)));
        System.out.println(map2);

        //分区partitioningBy 入参是个断言型接口
        studentList.stream()
                .collect(Collectors.partitioningBy((student) -> student.getScore() >= 60));

        //summarizingDouble 对某个值进行 数据统计输出
        //对score进行统计
        DoubleSummaryStatistics statistics = studentList.stream()
                .collect(Collectors.summarizingDouble(Student::getScore));
        statistics.getAverage();
        statistics.getCount();
        statistics.getMax();
        statistics.getMin();
        statistics.getSum();

 

Student类:

    private int id;
    private String name;
    private int age;
    private double score;
    private Clazz clazz;

    public Student(String name) {
        this.name = name;
    }

    public Student(int id, String name, int age, double score) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
    }

    public Student(int id, String name, int age, double score, Clazz clazz) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
        this.clazz = clazz;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

    public Clazz getClazz() {
        return clazz;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public String show() {
        return "测试方法引用";
    }

    @Override
    public int hashCode() {
        final int prime = 11;
        int hashCode = 1;
        hashCode = prime * hashCode + age;
        hashCode = prime * hashCode + id;
        hashCode = prime * hashCode + ((name == null) ? 0 : name.hashCode());
        long temp;
        temp = Double.doubleToLongBits(score);
        hashCode = prime * hashCode + (int) (temp ^ (temp >>> 32));
        return hashCode;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null) {
            return false;
        }

        if (getClass() != obj.getClass()) {
            return false;
        }
        Student other = (Student) obj;
        if (age != other.age) {
            return false;
        }

        if (id != other.id) {
            return false;
        }
        if (name == null) {
            if (other.name != null) {
                return false;
            }
        } else if (!name.equals(other.name)) {
            return false;
        }
        if (Double.doubleToLongBits(score) != Double.doubleToLongBits(other.score)) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "[id=" + id + ", name=" + name + ", age=" + age + ", score=" + score + ", Class=" + clazz + "]";
    }

    public static enum Clazz{
        Clazz1,
        Clazz2,
        Clazz3,
    }

 

Guess you like

Origin www.cnblogs.com/nijunyang/p/11334814.html