暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java新特性解读JDK8之函数式接口Consumer

227decision 2020-01-16
2048
Consumer作为消费型接口:有入参,无返回值

Consumer源码

    package java.util.function;
    import java.util.Objects;
    /**
    * Represents an operation that accepts a single input argument and returns no
    * result. Unlike most other functional interfaces, {@code Consumer} is expected
    * to operate via side-effects.
    *
    * <p>This is a <a href="package-summary.html">functional interface</a>
    * whose functional method is {@link #accept(Object)}.
    *
    * @param <T> the type of the input to the operation
    *
    * @since 1.8
    */
    @FunctionalInterface
    public interface Consumer<T> {


    /**
    * Performs this operation on the given argument.
    *
    * @param t the input argument
    */
    void accept(T t);
    }

    Consumer使用

      package com.example.functionalinterfacedemo;


      import java.util.Arrays;
      import java.util.List;
      import java.util.function.Consumer;


      public class ConsumerDemo {
      public static void main(String[] args) {

      //定义函数
      Consumer<String> consumer=obj->{
      System.out.println(obj+"消费完成");
      };
      consume("jack",consumer);

      //简单写法
      consume("tony",obj->{
      System.out.println(obj+"消费完成");
      });

      //常用于集合遍历
      List<String> asList = Arrays.asList("11","22","33");
      asList.forEach(obj->{System.out.println(obj);});

      }
      public static void consume(String name,Consumer<String> consumer){
      consumer.accept(name);
        }
      }


      最后修改时间:2020-07-01 13:37:31
      文章转载自227decision,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

      评论