java源码解读篇1:Consumer

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/likui19921224/article/details/89705045

Consumer<T> (消费者)

  java 1.8的函数式接口(@FunctionalInterface)
  
  接受单个参数并无返回结果的操作;
  1. void accept(T t);
    举例:
static   Consumer<Integer>mConsumer=(x)->{System.err.println(x+"");};	
	public static void main(String[] args) {
		mConsumer.accept(10);
	}
	

结果能够输出10:
accept的作用就是执行(消费)该参数,无返回参数 ;

2.default Consumer<T> andThen(Consumer<? super T> after) { Objects.requireNonNull(after); return (T t) -> { accept(t); after.accept(t); }; }
cosumer的default方法:
andthen :接受一个B消费者 并先调用A自身消费,返回一个消费者;
举例:


    static   Consumer<Integer>mConsumerA=(x)->{System.err.println(x+"");};
	static   Consumer<Object>mConsumerB=x->{if(x.getClass().isInstance(Integer.class)) {
		System.err.println(x+":是一个数字");
	}else  {
		System.err.println(x+":不是一个数字");
	}};
	public static void main(String[] args) {
		mConsumerA.andThen(mConsumerB).accept(10);;
	}

结果输出顺序分别是:A.accept(10),B.aceept(10);

下面我们看Consumer的使用地方 :

public class Utils {

    /**
     * Allows lambda iteration over a list. It is done in reverse order so it is safe
     * to add or remove items during the iteration.
     */
    public static <T> void safeForeach(List<T> list, Consumer<T> c) {
        for (int i = list.size() - 1; i >= 0; i--) {
            c.accept(list.get(i));
        }
    }

上面这段代码 来自于com.android.systemui.util包下的Utils 类,
SafeFoeach方法接受一个list 和一个消费参数;
遍历的时候我们调用每个元素给Consumer函数接口经行处理 而不期待他有任何的结果;

safefoeach方法只需要我们调用不同的consumer就可以得到不同的结果:如下:
1.(x)->{对x操作1}
2.(x)->{x操作2}

2.BiConsumer 和Consumer一样 不同的地方在于接受参数消费类型数量不一样;BiConsumer接受T,U两个参数类型

猜你喜欢

转载自blog.csdn.net/likui19921224/article/details/89705045