Introduction to the

Java8 has also been out for a long time, interface default methods, lambda expressions, functional interfaces, Date API and other features are still necessary to understand. For example, if a collection is often used in a project, lambda expressions can be used to traverse the collection. Stream is often used to filter and sort the collection. I’m used to it. I have to say it works. As a new feature of Java8, Stream is based on lambda expressions, which is an enhancement of collection object functions. It focuses on efficient and convenient aggregation operations or mass data operations on collection objects, improving programming efficiency and code readability. The principle of Stream: The element to be processed is considered a Stream. A Stream travels through a pipe and can be processed at the nodes of the pipe, including filtering, de-duplication, sorting, aggregation, and so on. The flow of elements in the pipe is processed through intermediate operations, and the final operation yields the result of the previous processing. Collections can generate streams in two ways:

  • Stream () − Creates a serial stream for the collection
  • ParallelStream () – Creates parallel streams for collections

The diagram above shows the class structure of the Stream class, which contains most of the intermediate and termination operations.

  • The intermediate operations mainly have the following methods (this type of method returns a Stream) : Map (mapToInt, flatMap, etc.), filter, distinct, sorted, peek, limit, Skip, parallel, sequential, and unordered
  • The operation can be terminated by the following methods: ForEach, forEachOrdered, toArray, Reduce, collect, min, Max, count, anyMatch, allMatch, noneMatch, findFirst, findAny, iterator

For example

First, to illustrate Stream operations on the collection of objects, create a new Student class overwriting equals() and hashCode() methods

public class Student {

    private Long id;

    private String name;

    private int age;

    private String address;

    public Student() {}

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() ! = o.getClass()) return false; Student student = (Student) o; return age == student.age && Objects.equals(id, student.id) && Objects.equals(name, student.name) && Objects.equals(address, student.address); } @Override public int hashCode() { return Objects.hash(id, name, age, address); } public Long getId() { return id; } public void setId(Long 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 String getAddress() { return address; } public void setAddress(String address) { this.address = address; }}Copy the code

Filter

public static void main(String [] args) {

        Student s1 = new Student(1L, "Xiao war", 15, "Zhejiang");
        Student s2 = new Student(2L, "Wang Yibo", 15, "Hubei");
        Student s3 = new Student(3L, "Andy", 17, "Beijing");
        Student s4 = new Student(4L, "Lee is now", 17, "Zhejiang");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);

        List<Student> streamStudents = testFilter(students); streamStudents.forEach(System.out::println); } /** * Set filter * @param students * @return
     */
    private static List<Student> testFilter(List<Student> students) {// Select students > 15 years old //returnstudents.stream().filter(s -> s.getAge()>15).collect(Collectors.toList()); // Select students who live in Zhejiang Provincereturn students.stream().filter(s ->"Zhejiang".equals(s.getAddress())).collect(Collectors.toList());
    }
Copy the code

Running results:

The map (conversion)

    public static void main(String [] args) {

        Student s1 = new Student(1L, "Xiao war", 15, "Zhejiang");
        Student s2 = new Student(2L, "Wang Yibo", 15, "Hubei");
        Student s3 = new Student(3L, "Andy", 17, "Beijing");
        Student s4 = new Student(4L, "Lee is now", 17, "Zhejiang");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);

        testMap(students); } /** * set conversion * @param students * @return
     */
    private static void testMap(List<Student> students) {List<String> addresses = students.stream().map(s ->"Address:"+s.getAddress()).collect(Collectors.toList());
        addresses.forEach(a ->System.out.println(a));
    }
Copy the code

The results

Distinct (go to)

    public static void main(String [] args) {

      testDistinct1(); } /** * set to redo (base type) */ private static voidtestDistinct1List<String> List = arrays.asList () {// Array <String> List = arrays.asList ("111"."222"."333"."111"."222");
        list.stream().distinct().forEach(System.out::println);
    }
Copy the code

Running results:

public static void main(String [] args) {

      testDistinct2(); } /** * collection to duplicate (reference objects) */ private static voidtestDistinct2() {// Dereference the reference object to implementhashStudent s1 = new Student(1L,"Xiao war", 15, "Zhejiang");
        Student s2 = new Student(2L, "Wang Yibo", 15, "Hubei");
        Student s3 = new Student(3L, "Andy", 17, "Beijing");
        Student s4 = new Student(4L, "Lee is now", 17, "Zhejiang");
        Student s5 = new Student(1L, "Xiao war", 15, "Zhejiang");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        students.add(s5);
        students.stream().distinct().forEach(System.out::println);
    }
Copy the code

Running results:

Sorted (sort)

    public static void main(String [] args) {

        testSort1(); } /** * Collection sort (default sort) */ private static voidtestSort1() {
        List<String> list = Arrays.asList("333"."222"."111");
        list.stream().sorted().forEach(System.out::println);
    }
Copy the code

Running results:

    public static void main(String [] args) {

        testSort2(); } /** * set sort (specify sort rules) */ private static voidtestSort2() {
        Student s1 = new Student(1L, "Xiao war", 15, "Zhejiang");
        Student s2 = new Student(2L, "Wang Yibo", 15, "Hubei");
        Student s3 = new Student(3L, "Andy", 17, "Beijing");
        Student s4 = new Student(4L, "Lee is now", 17, "Zhejiang");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        students.stream()
                .sorted((stu1,stu2) ->Long.compare(stu2.getId(), stu1.getId()))
                .sorted((stu1,stu2) -> Integer.compare(stu2.getAge(),stu1.getAge()))
                .forEach(System.out::println);
    }
Copy the code

Running results:

Limit (Limit the number of returns)

    public static void main(String [] args) {

        testLimit(); } /** * collectionlimitReturn the first few elements */ private static voidtestLimit() {
        List<String> list = Arrays.asList("333"."222"."111");
        list.stream().limit(2).forEach(System.out::println);
    }
Copy the code

Running results:

Skip (delete elements)

    public static void main(String [] args) {

        testSkip(); } /** * skip, delete the first n elements */ private static voidtestSkip() {
        List<String> list = Arrays.asList("333"."222"."111");
        list.stream().skip(2).forEach(System.out::println);
    }
Copy the code

Running results:

Reduce (polymerization)

    public static void main(String [] args) {
        testReduce(); } /** * set reduce, aggregate each element of the set into a single data */ private static voidtestReduce() {
        List<String> list = Arrays.asList("Huan"."Meet"."You");
        String appendStr = list.stream().reduce("Beijing",(a,b) -> a+b);
        System.out.println(appendStr);
    }
Copy the code

Running results:

Min (find the minimum)

    public static void main(String [] args) {
        testMin(a); } / private static void */ private static voidtestMin() {
        Student s1 = new Student(1L, "Xiao war", 14."Zhejiang");
        Student s2 = new Student(2L, "Wang Yibo", 15, "Hubei");
        Student s3 = new Student(3L, "Andy", 17, "Beijing");
        Student s4 = new Student(4L, "Lee is now", 17, "Zhejiang");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        Student minS = students.stream().min((stu1,stu2) ->Integer.compare(stu1.getAge(),stu2.getAge())).get();
        System.out.println(minS.toString());
    }
Copy the code

Running results:

AnyMatch allMatch/noneMatch (matching)

    public static void main(String [] args) {
        testMatch();
    }

    private static void testMatch() {
        Student s1 = new Student(1L, "Xiao war", 15, "Zhejiang");
        Student s2 = new Student(2L, "Wang Yibo", 15, "Hubei");
        Student s3 = new Student(3L, "Andy", 17, "Beijing");
        Student s4 = new Student(4L, "Lee is now", 17, "Zhejiang");
        List<Student> students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        Boolean anyMatch = students.stream().anyMatch(s ->"Hubei".equals(s.getAddress()));
        if (anyMatch) {
            System.out.println("There are Hubei people.");
        }
        Boolean allMatch = students.stream().allMatch(s -> s.getAge()>=15);
        if (allMatch) {
            System.out.println("All the students are over 15 years old.");
        }
        Boolean noneMatch = students.stream().noneMatch(s -> "Yang Yang".equals(s.getName()));
        if (noneMatch) {
            System.out.println("There is no student named Yang Yang."); }}Copy the code

The results

  • AnyMatch: Any element of the Stream that matches the predicate passed in returns true
  • AllMatch: All elements of the Stream match the predicate passed in, which returns true
  • NoneMatch: None of the elements in the Stream match the passed predicate, which returns true

conclusion

While the Stream traversal and manipulation can be done in the usual way, when the business logic is complex, you will find that the code is very large and unreadable, and you will write several lines of code for what one line of code does. Try lambda expressions, try Stream, and you’ll have a different experience.

The public,

Pay attention to the public number do not get lost