编程知识 cdmana.com

Lambda expression, functional programming integration

One 、 introduction

java8 The biggest feature is the introduction of Lambda expression , Functional programming , The act can be passed on . The conclusion is : Use immutable values and functions , Function to process immutable values , Map to another value .

Two 、java Important functional interfaces

1、 What is a functional interface

A function interface is an interface with only one abstract method , Used as a Lambda The type of expression . Use @FunctionalInterface Annotated class , The compiler will check if the class has only one abstract method or interface , otherwise , Will report a mistake . There can be multiple default methods , Static methods .

1.1 java8 Common functional interface provided by itself .

The function interface Abstract method function Parameters Return type Example
Predicate test(T t) Judge true or false T boolean 9 The height of a dragon is greater than 185cm Do you ?
Consumer accept(T t) News consumption T void Output a value
Function R apply(T t) take T It maps to R( Conversion function ) T R get student The name of the object
Supplier T get() Production news None T Factory method
UnaryOperator T apply(T t) Unitary operation T T Logic is not (!)
BinaryOperator apply(T t, U u) Binary operation (T,T) (T) Find the product of two numbers (*)
public class Test {
    
    @ToString
    static class OutstandingClass {
        private String name;
        private Student student;
        public String getName() {
            return name;
        }
        public Student getStudent() {
            return student;
        }
        
        public OutstandingClass(String name, Student student) {
            this.name = name;
            this.student = student;
        }
        public OutstandingClass() {
        }
    }
    
    @ToString
    static class Student{
         private String name;
         private int age;
         private int stature;
         private List<SpecialityEnum> specialitys;
         public Student(String name,int age,int height){
             this.name=name;
             this.age=age;
             this.stature=height;
         }
         public int getStature() {
             return stature;
         }
         public int getAge() {
             return age;
         }
         public String getName() {
             return name;
         }
         public List<SpecialityEnum> getSpecialitys() {
            return specialitys;
        }
    }
    
    @ToString
    static enum SpecialityEnum {
         SIGN("sing"),
         DANCE("dance"),
         SWIMMING("swimming"),
         RUNNING("running");
         private String speciality;
         public String getSpeciality() {
                return speciality;
         }
    //  Construction method , Be careful : The construction method cannot be public, because enum It can't be instantiated 
        private SpecialityEnum(String speciality) {
            this.speciality = speciality;
        }
    }
    
    public static void main(String[] args) {
        Predicate<Integer> predicate = x -> x > 185;
        Student student = new Student("9 dragon ", 23, 175);
        System.out.println(
            "9 The height of a dragon is higher than 185 Do you ?:" +           predicate.test(student.getStature()));

        Consumer<String> consumer = System.out::println;
        consumer.accept(" Fate is up to me ");

        Function<Student, String> function = Student::getName;
        String name = function.apply(student);
        System.out.println(name);

        Supplier<Integer> supplier = 
            () -> Integer.valueOf(BigDecimal.TEN.toString());
        System.out.println(supplier.get());

        UnaryOperator<Boolean> unaryOperator = uglily -> !uglily;
        Boolean apply2 = unaryOperator.apply(true);
        System.out.println(apply2);

        BinaryOperator<Integer> operator = (x, y) -> x * y;
        Integer integer = operator.apply(2, 3);
        System.out.println(integer);

        test(() -> " I'm a functional interface for demonstration ");
    }

    /**
     *  Demonstrate the use of custom functional interfaces 
     *
     * @param worker
     */
    public static void test(Worker worker) {
        String work = worker.work();
        System.out.println(work);
    }

    public interface Worker {
        String work();
    }
}
//9 The height of a dragon is higher than 185 Do you ?:false
// Fate is up to me 
//9 dragon 
//10
//false
//6
// I'm a functional interface for demonstration 

The above shows lambda Interface use and customize a functional interface and use . below , Let's see. java8 How to encapsulate the functional interface into the stream to help us deal with the collection efficiently .

Be careful :Student::getName This kind of writing in the example lambda The way of expression is called Method reference . The format is ClassNmae::methodName. Isn't that amazing ,java8 It's so charming .

1.2 Lazy evaluation and early evaluation

Lazy evaluation : Just describe Stream, The result of the operation is Stream, Such an operation is called lazy evaluation . Lazy evaluation can be chained like builder mode , Finally, we can use it as early as possible to get the final result .

Evaluate early : Get the final result instead of Stream, Such an operation is called early evaluation .

2、 Common stream

2.1 collect(Collectors.toList())

Convert the stream to list. also toSet(),toMap() etc. . Evaluate early .


List<Student> studentList = Stream.of(
    new Student(" Monkey D Luffy ", 22, 175),
    new Student(" Red hair ", 40, 180),
    new Student(" White beard ", 50, 185))
.collect(Collectors.toList());
System.out.println(studentList);

// Output results 
//[Student{name=' Monkey D Luffy ', age=22, stature=175, specialities=null}, 
//Student{name=' Red hair ', age=40, stature=180, specialities=null}, 
//Student{name=' White beard ', age=50, stature=185, specialities=null}]

2.2 filter

seeing the name of a thing one thinks of its function , rise Filter and filter The role of . The internal is Predicate Interface . Lazy evaluation .

For example, we screened out the height less than 180 Classmate .

List<Student> students = new ArrayList<>(3);
        students.add(new Student(" Monkey D Luffy ", 22, 175));
        students.add(new Student(" Red hair ", 40, 180));
        students.add(new Student(" White beard ", 50, 185));

        List<Student> list = students.stream()
            .filter(stu -> stu.getStature() < 180)
            .collect(Collectors.toList());
        System.out.println(list);
        
// Output results 
//[Student{name=' Monkey D Luffy ', age=22, stature=175, specialities=null}]

2.3 map

Conversion function , The internal is Function Interface . Lazy evaluation

List<Student> students = new ArrayList<>(3);
        students.add(new Student(" Monkey D Luffy ", 22, 175));
        students.add(new Student(" Red hair ", 40, 180));
        students.add(new Student(" White beard ", 50, 185));

        List<String> names = students.stream().map(student -> student.getName())
                .collect(Collectors.toList());
        System.out.println(names);
        
// Output results 
//[ Monkey D Luffy ,  Red hair ,  White beard ]

In the example student Object to String object , obtain student Name .

2.4 flatMap

Will be multiple Stream Merge into one Stream. Lazy evaluation

List<Student> students = new ArrayList<>(3);
        students.add(new Student(" Monkey D Luffy ", 22, 175));
        students.add(new Student(" Red hair ", 40, 180));
        students.add(new Student(" White beard ", 50, 185));

        List<Student> studentList = Stream.of(students,
                asList(new Student(" ACE ", 25, 183),
                        new Student(" Raleigh ", 48, 176)))
                .flatMap(students1 -> students1.stream()).collect(Collectors.toList());
        System.out.println(studentList);
        
// Output results 
//[Student{name=' Monkey D Luffy ', age=22, stature=175, specialities=null}, 
//Student{name=' Red hair ', age=40, stature=180, specialities=null}, 
//Student{name=' White beard ', age=50, stature=185, specialities=null}, 
//Student{name=' ACE ', age=25, stature=183, specialities=null},
//Student{name=' Raleigh ', age=48, stature=176, specialities=null}]

call Stream.of The static method will be two list Convert to Stream, Re pass flatMap Merge two streams into one .

2.5 max and min

We are often in the assembly Find the maximum or minimum value , It's easy to use streams . Evaluate early .

List<Student> students = new ArrayList<>(3);
        students.add(new Student(" Monkey D Luffy ", 22, 175));
        students.add(new Student(" Red hair ", 40, 180));
        students.add(new Student(" White beard ", 50, 185));

        Optional<Student> max = students.stream()
            .max(Comparator.comparing(stu -> stu.getAge()));
        Optional<Student> min = students.stream()
            .min(Comparator.comparing(stu -> stu.getAge()));
        // Judge whether there is value 
        if (max.isPresent()) {
            System.out.println(max.get());
        }
        if (min.isPresent()) {
            System.out.println(min.get());
        }
        
// Output results 
//Student{name=' White beard ', age=50, stature=185, specialities=null}
//Student{name=' Monkey D Luffy ', age=22, stature=175, specialities=null}

max、min Receive one Comparator( Use... In the example java8 Built in static functions , Just pass in and compare values .) And return to a Optional object , The object is java8 New class , To prevent null Null pointer exception thrown . have access to max.isPresent() Judge whether there is value ; have access to max.orElse(new Student()), The duty of null Use the given value ; You can also use max.orElseGet(() -> new Student()); This needs to introduce a Supplier Of lambda expression .

2.6 count

Statistical function , It's usually a combination filter Use , Because first we need to screen out the statistics can . Evaluate early

List<Student> students = new ArrayList<>(3);
        students.add(new Student(" Monkey D Luffy ", 22, 175));
        students.add(new Student(" Red hair ", 40, 180));
        students.add(new Student(" White beard ", 50, 185));

        long count = students.stream().filter(s1 -> s1.getAge() < 45).count();
        System.out.println(" Age is less than 45 The number of people aged is :" + count);
        
// Output results 
// Age is less than 45 The number of people aged is :2

2.7 reduce

reduce Operation can generate a value from a set of values . Used in the above example count 、 min and max Fang Law , It is included in the standard library because it is commonly used . in fact , All of these methods are reduce operation . Evaluate early .
image

Integer reduce = Stream.of(1, 2, 3, 4).reduce(0, (acc, x) -> acc+ x);
        System.out.println(reduce);
// Output results 
//10

We can see reduce Received an initial value of 0 The accumulator of , Take out the value and add it to the accumulator one by one , The value of the final accumulator is the final result .

3、 ... and 、 Advanced collection classes and collectors

The collector , A universal 、 A structure that generates complex values from a stream . Just pass it on to collect Method , All streams can use it . The standard class library already provides some useful collectors , The collectors in the following example code are all from java.util.stream.Collectors Class .

List<Student> students1 = new ArrayList<>(3);
students1.add(new Student(" Monkey D Luffy ", 23, 175));
students1.add(new Student(" Red hair ", 40, 180));
students1.add(new Student(" White beard ", 50, 185));
OutstandingClass ostClass1 = new OutstandingClass(" Class one ", students1);
// Copy students1, And remove a student 
List<Student> students2 = new ArrayList<>(students1);
students2.remove(1);
OutstandingClass ostClass2 = new OutstandingClass(" Class two ", students2);
// take ostClass1、ostClass2 Convert to Stream
Stream<OutstandingClass> classStream = Stream.of(ostClass1, ostClass2);
OutstandingClass outstandingClass = biggestGroup(classStream);
System.out.println(" The class with the largest number is :" + outstandingClass.getName());
System.out.println(" The average age of class one is :" + averageNumberOfStudent(students1));

/**
 *  Get the largest number of classes 
 */
public static OutstandingClass biggestGroup(Stream<OutstandingClass> outstandingClasses) {
    return outstandingClasses.collect(
            maxBy(comparing(ostClass -> ostClass.getStudents().size())))
            .orElseGet(OutstandingClass::new);
}
/**
 *  Calculate the average age 
 */
private static double averageNumberOfStudent(List<Student> students) {
    return students.stream().collect(averagingInt(Student::getAge));
}

// Output results 
// The class with the largest number is : Class one 
// The average age of class one is :37.666666666666664

maxBy perhaps minBy Is to find the maximum value and the minimum value .

3.2 Convert to a block

A common stream operation is to break it down into two sets ,Collectors.partitioningBy Helped us to achieve , Receive one Predicate Functional interface .
image
The sample students are divided into two groups: those who can sing and those who can't .

Map<Boolean, List<Student>> listMap = students.stream().collect(
            Collectors.partitioningBy(student -> student.getSpecialities().
                                      contains(SpecialityEnum.SING)));

3.3 The data packet

Data grouping is a more natural way to segment data , And divide the data into ture and false The two parts are different , You can make Group data with any value .Collectors.groupingBy Receive one Function Do the conversion .

image
Pictured , We use groupingBy Group into a group of circles according to , A set of triangles , A set of squares .

Example : Group students according to their first specialty

Map<SpecialityEnum, List<Student>> listMap = 
             students.stream().collect(
             Collectors.groupingBy(student -> student.getSpecialities().get(0)));

Collectors.groupingBy And SQL Medium group by The operation is the same .

3.4 String splicing

If you put together the names of all the students , How to do it? ? Usually only one... Can be created StringBuilder, Cyclic splicing . Use Stream, Use Collectors.joining() Simple and easy .**

List<Student> students = new ArrayList<>(3);
        students.add(new Student(" Monkey D Luffy ", 22, 175));
        students.add(new Student(" Red hair ", 40, 180));
        students.add(new Student(" White beard ", 50, 185));

         String names = students.stream()
             .map(Student::getName).collect(Collectors.joining(",","[","]"));
        System.out.println(names);
        
// Output results 
//[ Monkey D Luffy , Red hair , White beard ]

joining Receive three parameters , The first is the delimiter , The second is the prefix , The third is the closing sign . You can also pass in no parameters Collectors.joining(), This is the direct splicing .

3.5 Screening +-

static class Student{
    public String name;
     public int age;
     public int stature;
     public boolean result;
     public Student(String name,int age,int height,boolean result){
            this.name=name;
     this.age=age;
     this.stature=height;
     this.result=result;
 }
    public void setResult(boolean result){
        this.result= result;
 }
    public int getStature() {
        return stature;
 }
    public int getAge() {
        return age;
 }
    public String getName() {
        return name;
 }
    public boolean getResult() {
        return result;
 }
}
public static void main(String[] args) {
    List<String> iv=new ArrayList();
 iv.add(" Zhang San ");
 iv.add(" Li Si ");
 iv.add(" Wang Wu ");
 iv.add(" Zhao Liu ");
 List<Student> troList =new ArrayList();
 troList.add(new Student("bobo",20,170,false));
 troList.add(new Student(" Zhang San ",30,171,false));
 troList.add(new Student(" Lao Li ",40,172,false));
 troList.add(new Student(" Zhao Liu ",50,173,false));
 troList.add(new Student(" Next to the Lao wang ",60,174,false));
 // Screening +
 List<String> stringList = iv.stream().filter(
            tname -> troList.stream().map(Student::getName).collect(Collectors.toList()).contains(tname)
    ).collect(Collectors.toList());
 List<Student> students = troList.stream().map(
            student -> {
                if(iv.contains(student.getName())){
                    student.setResult(true);
 return student;
 }
                return student;
 }
    ).collect(Collectors.toList());
 students.forEach(
            s -> {
                System.out.println(s.getName() +":" + s.getResult());
 }
    );
 System.out.println("================ Screening +===============");
 stringList.forEach(
            s -> {
                System.out.println(s);
 }
    );
 System.out.println("================ Screening -===============");
 // Screening -
 List<String> stringList2 = iv.stream().filter(
            tname -> !troList.stream().map(Student::getName).collect(Collectors.toList()).contains(tname)
    ).collect(Collectors.toList());
 stringList2.forEach(
            s -> {
                System.out.println(s);
 }
    );
}

Four 、 summary

This article mainly describes the commonly used methods and flows from the actual use , Use java8 Can be very clear about what you want to do , The code is also very concise . The main purpose of this example is to explain more simply , You can use java8 Refactor your existing code , Grasp by oneself lambda The mystery of . What this article says Stream It needs to be combined to play a greater function , Chain calls are fascinating , Do it according to your business .

版权声明
本文为[isWulongbo]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224163424925r.html

Scroll to Top