[Java] Lambda expression and Stream flow based on Java

table of Contents

Lambda expression

Functional interface

1、Supplier

2、Consumer

3、Predicate

4、Function

Stream

How to obtain Stream:

Common methods:


Lambda expression

        Lambda expressions, which can also be called closures, are an important feature of Java 8. Using Lambda expressions can make the code more concise and compact.

   Lambda format: three parts:

        1) Some parameters 2) An arrow 3) Some codes

standard format:

         (Parameter)->{some code};

Omission rule

  • The parameter data type in parentheses can be omitted directly

  • If there is only one parameter in the parentheses, the parentheses can be omitted directly

  • If there is only one code in the braces, regardless of whether there is a return value, you can omit the return keyword, braces and semicolons at the same time.

// 1. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)  
(String s) -> System.out.print(s)

// 2. 接收2个int型整数,返回他们的和  
(int x, int y) -> x + y  
  
// 3. 接受2个参数(数字),并返回他们的差值  
(x, y) -> x – y 
  
// 4. 接收一个参数(数字类型),返回其2倍的值  
x -> 2 * x 

// 5. 不需要参数,返回值为 
() -> 5  

The premise of using lambda expressions:

       1) using the lambda must have an interface , and requires only one abstract method and               either built into JDK Runnable, Comparator interfaces or custom interfaces, abstract method only when the interface is present and only be used when Lambda

        2 ) The use of lambda expressions must have context inference                  , that is, the parameter or local variable type of the method must be the interface type corresponding to the lambda in order to use Lambda as an instance of the interface 

        If an interface has only one abstract method, this interface is called a functional interface (it has nothing to do with other non-abstract methods) . If you don’t know whether this is a functional interface, you can use the annotation @FunctionalInterface to check whether the current interface is a functional interface

Functional interface

Next, we will introduce four common functional interfaces.

1、Supplier<T>

1) java.util.function.Supplier<T>: The interface only contains a method without parameters, T get(): used to obtain the object data of a generic parameter execution type, because this interface is a functional interface, namely The corresponding Lambda expression needs to provide the data of an object conforming to the generic type.

     This interface is a production interface. Specify what type of generic interface is, then what type of data will be generated by the get method in the interface

public class DemoSupplier {
    public static void main(String[] args) {
        //调用getString方法,方法参数supplier是一个函数式接口,所以可以传递lambda表达式
        String s=getString(()-> {
            //生产一个字符串,并返回
            return "James";
        });
        String s1 = getString(()->"Jerry");
        System.out.println(s);
        System.out.println(s1);
    }
    //定义一个方法,方法的参数 传递supplier<T>接口,泛型执行string,get方法就会返回一个string
    public  static  String getString(Supplier<String>supplier){
        return supplier.get();
    }
}

2、Consumer<T>

        java.util.function.Consumer<T>: This interface is just the opposite of the Supplier interface. Supplier is an interface for producing data, while Consumer is an interface for consuming data, and its data type is also determined by generics.

        The Consumer interface contains the abstract method void accept(T t), which means to consume a specified generic data

public class DemoConsumer {
    public static void main(String[] args) {
        //调用method犯法,传递字符串姓名,方法的另一个参数是Consumer接口,
        //是一个函数式接口,所以可以传递Lambda表达是
        method("James", (String name)->{
            //对传递的字符串进行消费
            //消费方式:直接输出字符串
            System.out.println (name);
            //翻转字符串
            String reName=new StringBuffer(name).reverse().toString();
            System.out.println( reName);
        });
    }
    public static void method(String name, Consumer<String>con){
        con.accept(name);
    }
}

3、Predicate<T>

java.util.function.Predicate<T> interface: used to judge a certain type to obtain a boolean value. The Predicate interface contains an abstract method: boolean test (T t).

public class DemoPredicate {
    public static void main(String[] args) {
        //定义一个字符串
        String s = "abcdefg";
        //调用checkstring方法对字符串进行校验,参数传递字符串和lambda表达式
        boolean b = checkString(s, (str) ->
                //对参数进行传递的字符串进行判断,判断字符串的长度是否大于5,并把判断的结果返回
                str.length() > 7);
        System.out.println(b);
    }

    public static boolean checkString(String s, Predicate<String> predicate) {
        return predicate.test(s);
    }
}

4、Function<T>

       java.util.function.Function<T R>: This interface is used to get a type of data according to a type of data. The former is called a pre-condition and the latter is called a post-condition.

        The main abstract method in the Function interface is R apply (T t), which obtains the interface of type R according to the parameters of type T.

public class DemoFunction {
    public static void main(String[] args) {
        //定义一个字符串类型整数
        String s="124";
        //调用change方法,传递字符串类型的整数和lambda表达式
        change(s,(str)->Integer.parseInt(s));
    }
    public static void change(String s,Function<String,Integer> function){
        int in=function.apply(s);
        System.out.println(in);
    }
}

Stream

       Stream is used to solve the disadvantages of existing collection libraries. Stream stream benefits from the function of Lambda, because there is Lambda expression to have Stream stream

How to obtain Stream:

1) Collection single column collection: collection.stream()

2) Array: Stream.of (array)

3) Map two-column collection:

        Set.keySet().stream() ---》j key

        Collection.values().stream() --- "value

package com.itheima_06;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

public class Test01 {
    public static void main(String[] args) {
        //把集合和数组转化成Stream流

        //单列集合
        ArrayList<Integer> list = new ArrayList<>();
        list.add(123);
        list.add(456);
        list.add(789);

        //把单列集合转化成Stream流
        Stream<Integer> stream1 = list.stream();
        
        
        //双列集合(扩展)
        //双列集合不能转成Stream,需要把键和值单独转化
        Map<Integer,String> map = new HashMap<>();
        map.put(1,"柳岩");
        map.put(2,"张三");
        
        //把双列集合转成Stream流
        //键
        Stream<Integer> stream2 = map.keySet().stream();
        //值
        Stream<String> stream3 = map.values().stream();
        
        //数组
        Integer[] arr = {11,22,33,44};

        Stream<Integer> stream4 = Stream.of(arr);
    }
}

Common methods:

1. Final method: It means that no other methods of the stream can be called after the call.

  • count(): returns the number of elements in the stream
  • forEach(): Traverse elements --- " The parameter passed by forEach is the Consumer<T> interface
//forEach使用
public class Demo01 {
    public static void main(String[] args) {
        //创建list集合
        List<String >list = new ArrayList<>();
        Collections.addAll(list,"张三丰","王思聪","张飞","刘晓敏","张靓颖");
        //使用stream流打印数据
        Stream<String> stream = list.stream();
        stream.forEach(s-> System.out.println(s));
    }
}

//count使用
public class Demo03 {
    public static void main(String[] args) {
        //创建list集合
        List<String > list = new ArrayList<>();
        Collections.addAll(list,"张三丰","王思聪","张飞","刘晓敏","张靓颖");
        //使用stream流打印数据
        Stream<String> stream = list.stream();
        //筛选所有“张"姓学员
        long l = stream.filter(s -> s.startsWith("张")).count();
        System.out.println("张姓学员为"+l+"个");
    }
}

Non-terminal method: refers to other methods that can continue to call the stream after the stream is called

  • filter(): Filter method ----》The parameter passed by filter is the Predicate interface
  • limit(): Take the first few
  • skip(): skip the first few
  • map(): A mapping method that can convert elements from one type to another type ----》The interface passed by map is the Function interface
  • static concat(): Combine two streams into one Stream
public class Demo02 {
    public static void main(String[] args) {
        //创建list集合
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "张三丰", "王思聪", "张飞", "刘晓敏", "张靓颖");
        //使用stream流打印数据
        Stream<String> stream = list.stream();
        stream.filter(s -> s.startsWith("张")).forEach(s ->System.out.println(s));
    }
}


public class Demo04 {
    public static void main(String[] args) {
        //创建list集合
        List<String > list = new ArrayList<>();
        Collections.addAll(list,"张三丰","王思聪","张飞","刘晓敏","张靓颖","王敏");
        //使用stream流打印数据
        Stream<String> stream = list.stream();
        //筛选集合中所有张姓学员
        stream.filter(s->s.startsWith("张")).limit(2).forEach(s-> System.out.println(s));
        System.out.println("=============================");
        //重新获取stream流
        Stream<String>stream1= list.stream();
        //筛选所有王姓人员
        stream1.filter(s->s.startsWith("王")).skip(1).forEach(s-> System.out.println(s));
    }
}



public class Demo05 {
    public static void main(String[] args) {
        //创建list集合
        List<String > list = new ArrayList<>();
        Collections.addAll(list,"张三丰","王思聪","张飞","刘晓敏","张靓颖","王敏");
        //使用stream流打印数据
        Stream<String> stream = list.stream();
        //使用map()方法将每个元素封装为一个Person对象(创建一个Person类,name属性)
        List<Person> collect = stream.map(s -> new Person(s)).collect(Collectors.toList());
        System.out.println(collect);
    }
}


public class Demo05 {
    public static void main(String[] args) {
        //创建list集合
        List<String> list = new ArrayList<>();
        Collections.addAll(list, "张三丰", "王思聪", "张飞", "刘晓敏", "张靓颖", "王敏");
        //使用stream流打印数据
        Stream<String> stream = list.stream();
        //筛选集合中所有张姓学员
        stream = stream.filter(s -> s.startsWith("张"));
        System.out.println("=============================");
        //重新获取stream流
        Stream<String> stream1 = list.stream();
        //筛选所有王姓人员
        stream1 = stream1.filter(s -> s.startsWith("王"));
        //合并流
        Stream<String> stream2 = Stream.concat(stream, stream1);
        stream2.forEach(s -> System.out.println(s));
    }
}

 

Guess you like

Origin blog.csdn.net/weixin_43267344/article/details/108095511