Lambda common methods

preface

This article briefly summarizes the common methods in Lambda

For students unfamiliar with Lambda, please refer to this article for introduction Understanding of Lambda , Lambda is really more comfortable

If you are new to Lambda, but are not familiar with Consumer, Supplier, Predicate and Function, please refer to this article Quick understanding of Consumer, Supplier, Predicate and Function

If you are already familiar with Lambda, but you don't understand its execution principle, please refer to my article Lambda execution principle

Let's start with an example

Here are five students. Put them into the group

       @Data
       @AllArgsConstructor
       class Student {
           private String name;
           private Integer age;
       }      


        Student a = new Student("a", 20);
        Student b = new Student("b", 18);
        Student c = new Student("c", 22);
        Student d = new Student("d", 19);
        Student e = new Student("e", 18);
        List<Student> list = new ArrayList<>();
        list.add(a);
        list.add(b);
        list.add(c);
        list.add(d);
        list.add(e);

In daily development, there may be the following requirements:

1, Traverse the set

        list.forEach(System.out::println);

forEach accepts a Consumer expression

2, Take out the student's name

        List<String> nameList = list.stream()
                .map(Student::getName)
                .collect(Collectors.toList());

Stream can transform one form of stream into another. The code above is to transform the stream containing the whole student object into a stream containing names separately. Finally, collect the stream.

3, Take out students older than 19

        List<Student> studentList = list.stream()
                .filter(s -> s.getAge() > 19)
                .collect(Collectors.toList());

The filter receives a Predicate expression and discards the student objects that do not match the expression in the stream.

4, Take out the age of students without repetition

        List<Integer> ageDistinctList = list.stream()
                .map(Student::getAge)
                .distinct()
                .collect(Collectors.toList());

Just like mysql's de duplication keyword, it uses distinct

5, Full match, any match, none match

Requirement 1: whether all students are over the age of 18 (full match)

        boolean flag = list.stream()
                .map(Student::getAge)
                .allMatch(i -> i > 18);

Requirement 2: whether there are students older than 21 (any matching)

        boolean flag = list.stream()
                .map(Student::getAge)
                .anyMatch(i -> i > 21);

Requirement 3: whether all students are no older than 22 (no match)

        boolean flag = list.stream()
                .map(Student::getAge)
                .noneMatch(i -> i > 22);

6, Sort

Needs, sorted by age of student

        list.stream()
                .sorted(Comparator.comparingInt(Student::getAge))
                .forEach(System.out::println);

Output:

The default is to output in ascending order according to age, or in descending order, as long as.reversed is added, as shown in the following figure

        list.stream()
                .sorted(Comparator.comparingInt(Student::getAge).reversed())
                .forEach(System.out::println);

If you sort by age and then by name, you can write:

        list.stream()
                .sorted(Comparator.comparingInt(Student::getAge).thenComparing(Student::getName))
                .forEach(System.out::println);

7, Pagination

Requirement: the current page is page 2, with 3 items per page

        list.stream()
                .sorted(Comparator.comparingInt(Student::getAge))
                .skip((2 - 1) * 3) //(current page - 1) * number of items displayed per page
                .limit(3)          //Number of items per page
                .forEach(System.out::println);

First, sort by age, then skip the data on the previous page and take out the limit data.

8, Grouping

Needs: grouped by age

        Map<Integer, List<Student>> group = list.stream().collect(Collectors.groupingBy(Student::getAge));
        group.forEach((k, v) -> System.out.println("k:" + k + ",v:" + v.toString()));

Output:

9, String splicing

Requirement: output comma separated string of student name

        String str = list.stream().map(Student::getName).collect(Collectors.joining(","));
        System.out.println(str);

Output:

10, Mathematical operation

Demand 1: find the total age of students

        int sum = list.stream().mapToInt(Student::getAge).sum();
        System.out.println(sum);

Demand 2: average age of students

        double average = list.stream()
                .mapToInt(Student::getAge)
                .average()
                .orElse(0.0);
        System.out.println(average);

Note that average() returns an OptionalDouble, and in order to prevent the collection from having no elements, we must use orElse to specify a default value.

Similarly, max is used to get the maximum value, min is used to get the minimum value, and the default value needs to be specified.

Continue to add cases

 

 

 

 

Keywords: Lambda MySQL

Added by Jazzy Girl on Wed, 10 Jun 2020 05:40:45 +0300