Java8 the Consumer, Supplier, Predicate and Function Raiders

Today we talk about Consumer, Supplier, Predicate, Function use these interfaces in use Java8 among these interfaces Although there is no blatant use, however, it is moisten things silently. Why do you say?

These interfaces are java.util.functionunder the package, namely the Consumer (consumer), supplier (supply-side), predicate (predicate type), function (functional), with the latter believed to explain, you should be very aware of this interface the function.

So, here, we have to say something about this use of the interface from the specific application scenario!

1 Consumer Interface

From the literal meaning we can see it, consumer接口is a consumer-oriented interfaces, by passing parameters, then the output value is so simple, some methods Java8 looks very abstract, in fact, as long as you understand it felt very easy to use, and very simple.

Here we look at an example, and then let's analyze this interface.

1.1 Consumer examples

/**
     * consumer接口测试
     */
    @Test
    public void test_Consumer() {
        //① 使用consumer接口实现方法
        Consumer<String> consumer = new Consumer<String>() {

            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        };
        Stream<String> stream = Stream.of("aaa""bbb""ddd""ccc""fff");
        stream.forEach(consumer);

        System.out.println("********************");

        //② 使用lambda表达式,forEach方法需要的就是一个Consumer接口
        stream = Stream.of("aaa""bbb""ddd""ccc""fff");
        Consumer<String> consumer1 = (s) -> System.out.println(s);//lambda表达式返回的就是一个Consumer接口
        stream.forEach(consumer1);
        //更直接的方式
        //stream.forEach((s) -> System.out.println(s));
        System.out.println("********************");

        //③ 使用方法引用,方法引用也是一个consumer
        stream = Stream.of("aaa""bbb""ddd""ccc""fff");
        Consumer consumer2 = System.out::println;
        stream.forEach(consumer);
        //更直接的方式
        //stream.forEach(System.out::println);
    }

Output

1.2 Case Study

consumerInterface Analysis

① in the code, we create a direct Consumerinterface, and implements a named acceptmethod, this method is the key to this interface.

We look at the acceptmethod; this method to pass a parameter does not return a value. When we find forEachthe need for a Consumertype of argument when, after passing, you can output the corresponding value.

② lambda expressions as consumer

Consumer<String> consumer1 = (s) -> System.out.println(s);//lambda表达式返回的就是一个Consumer接口

In the above code, we use the following lambdaexpression as Consumer. Carefully look you will find lambdaan expression that returns a value Consumer; therefore, you will be able to understand why the forEachmethod can be used lamdda expression as an argument instead.

③ Method incorporated consumer

Consumer consumer2 = System.out::println;

In the above code, we used a method reference aspect as a Consumer, also be passed to forEachthe method.

1.3 Other Consumer Interface

In addition to the above-Consumer interface, the following may also be used Consumer these interfaces.
IntConsumer、DoubleConsumer、LongConsumer、BiConsumerUsing the same method as above.

1.4 Consumer summary

After reading the above examples we can be summarized as points.

① Consumer is an interface, and as long as the realization of a acceptmethod, can be used as a "consumer" output.
② In fact, lambda expressions, method return values are quoted Consumer types , so they can be used as forEachmethod parameters, and outputs a value.

2 Supplier Interface

Supplier Interface is a supply-type interface, in fact, that white is a container that can be used to store data, then such an interface can be used for other methods, is not very clear, if still do not understand, look at the following example must thoroughly get to know!

2.1 Supplier examples

**
     * Supplier接口测试,supplier相当一个容器或者变量,可以存储值
     */
    @Test
    public void test_Supplier() {
        //① 使用Supplier接口实现方法,只有一个get方法,无参数,返回一个值
        Supplier<Integer> supplier = new Supplier<Integer>() {
            @Override
            public Integer get() {
                //返回一个随机值
                return new Random().nextInt();
            }
        };

        System.out.println(supplier.get());

        System.out.println("********************");

        //② 使用lambda表达式,
        supplier = () -> new Random().nextInt();
        System.out.println(supplier.get());
        System.out.println("********************");

        //③ 使用方法引用
        Supplier<Double> supplier2 = Math::random;
        System.out.println(supplier2.get());
    }

Output

2.2 Case Study

① Supplier Interface analysis
java Supplier<Integer> supplier = new Supplier<Integer>() { @Override public Integer get() { //返回一个随机值 return new Random().nextInt(); } }; ¨G4G java //② 使用lambda表达式, supplier = () -> new Random().nextInt(); System.out.println(supplier.get()); System.out.println("********************"); ¨G5G java //③ 使用方法引用 Supplier<Double> supplier2 = Math::random; System.out.println(supplier2.get()); ¨G6G java /** * Supplier接口测试2,使用需要Supplier的接口方法 */ @Test public void test_Supplier2() { Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5); //返回一个optional对象 Optional<Integer> first = stream.filter(i -> i > 4) .findFirst(); ¨K32K ¨G7G java Optional<Integer> first = stream.filter(i -> i > 4) .findFirst(); ¨G8G java //optional对象有需要Supplier接口的方法 //orElse,如果first中存在数,就返回这个数,如果不存在,就放回传入的数 System.out.println(first.orElse(1)); System.out.println(first.orElse(7)); ¨K33K ¨G9G java /** * Predicate谓词测试,谓词其实就是一个判断的作用类似bool的作用 */ @Test public void test_Predicate() { //① 使用Predicate接口实现方法,只有一个test方法,传入一个参数,返回一个bool值 Predicate<Integer> predicate = new Predicate<Integer>() { @Override public boolean test(Integer integer) { if(integer > 5){ return true; } return false; } }; ¨K34K ¨G10G java //① 使用Predicate接口实现方法,只有一个test方法,传入一个参数,返回一个bool值 Predicate<Integer> predicate = new Predicate<Integer>() { @Override public boolean test(Integer integer) { if(integer > 5){ return true; } return false; } }; ¨G11G System.out.println(predicate.test(6)); ¨G12G java //② 使用lambda表达式, predicate = (t) -> t > 5; System.out.println(predicate.test(1)); System.out.println("********************"); ¨G13G java /** * Predicate谓词测试,Predicate作为接口使用 */ @Test public void test_Predicate2() { //① 将Predicate作为filter接口,Predicate起到一个判断的作用 Predicate<Integer> predicate = new Predicate<Integer>() { @Override public boolean test(Integer integer) { if(integer > 5){ return true; } return false; } }; ¨K35K ¨G14G java Stream<Integer> stream = Stream.of(1, 23, 3, 4, 5, 56, 6, 6); List<Integer> list = stream.filter(predicate).collect(Collectors.toList()); list.forEach(System.out::println); ¨G15G java /** * Function测试,function的作用是转换,将一个值转为另外一个值 */ @Test public void test_Function() { //① 使用map方法,泛型的第一个参数是转换前的类型,第二个是转化后的类型 Function<String, Integer> function = new Function<String, Integer>() { @Override public Integer apply(String s) { return s.length();//获取每个字符串的长度,并且返回 } }; ¨K36K ¨G16G java //① 使用map方法,泛型的第一个参数是转换前的类型,第二个是转化后的类型 Function<String, Integer> function = new Function<String, Integer>() { @Override public Integer apply(String s) { return s.length();//获取每个字符串的长度,并且返回 } }; ¨G17G Stream<String> stream = Stream.of("aaa", "bbbbb", "ccccccv"); Stream<Integer> stream1 = stream.map(function); stream1.forEach(System.out::println);
in Functionimportant application interfaces have to say that Streamthe class mapmethod, the mapmethod passing a Functionport, return a converted Streamclass.

4.3 Other Function Interface

In addition to the above-Function interface, the following may also be used such Function interfaces.
IntFunction, DoubleFunction, LongFunction, ToIntFunction, ToDoubleFunction, DoubleToIntFunction the like, using the same method as above.

4.4 Function Interface summary

① Function Interface is a functional interface is a converted effect data.
② Function interface applymethod to do the conversion.

5 summary

By the previous description, already Consumer、Supplier、Predicate、Functionhas a detailed understanding of these interfaces, but in fact, these interfaces is not difficult, just a little abstract, to pay more will find it simple to understand, and is particularly useful!

Articles have inappropriate, please correct me, if you like micro-letters to read, you can also concerned about my micro-channel public number : , 好好学javaaccess to quality learning resources.

Guess you like

Origin sihailoveyan.iteye.com/blog/2443152