java consumer_Java8 Consumer&BiConsumer使用

java8里面consumer&BiConsumer也是函数式接口,从代码上看,consumer只有一个入参,没有返回值;BiConsumer两个入参,没有返回值。

1、Consumer简单例子

package com.cattles.function;

import java.util.function.Consumer;

/**

* @author cattle - 稻草鸟人

* @date 2020/4/12 下午3:04

*/

public class Java8Consumer1 {

public static void main(String[] args) {

Consumer stringConsumer = x -> System.out.println("hello!" + x);

stringConsumer.accept("cattle");

}

}

输出:

hello!cattle

2、Consumer当做参数传输

package com.cattles.function;

import java.util.Arrays;

import java.util.List;

import java.util.function.Consumer;

/**

* @author cattle - 稻草鸟人

* @date 2020/4/12 下午3:13

*/

public class Java8Consumer2 {

public static void main(String[] args) {

List integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);

Consumer integerConsumer = x -> System.out.println(x);

forEach(integers, integerConsumer);

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

forEach(integers, x -> System.out.println(x));

}

static void forEach(List list, Consumer consumer) {

list.forEach(consumer);

}

}

输出:

1

2

3

4

5

6

7

8

===========

1

2

3

4

5

6

7

8

3、BiConsumer简单例子

package com.cattles.function;

import java.util.function.BiConsumer;

/**

* @author cattle - 稻草鸟人

* @date 2020/4/12 下午3:20

*/

public class Java8BiConsumer1 {

public static void main(String[] args) {

BiConsumer add = (x, y) -> System.out.println(Math.addExact(x, y));

add.accept(1, 2);

}

}

输出

3

4、BiConsumer当做参数传输

package com.cattles.function;

import java.util.function.BiConsumer;

/**

* @author cattle - 稻草鸟人

* @date 2020/4/12 下午3:23

*/

public class Java8BiConsumer2 {

public static void main(String[] args) {

add(1, 2, (x, y) -> System.out.println(x + y));

add("Hello!", "Cattle", (x, y) -> System.out.println(x + y));

}

static void add(T a, T b, BiConsumer c) {

c.accept(a, b);

}

}

输出:

3

Hello!Cattle

5、Map.forEach例子

在第2点,consumer当做参数例子里面,我们发现list的forEach代码参数是Consumer,而map里面的forEach参数则使用的是BiConsumer,下面我们看下例子

package com.cattles.function;

import java.util.HashMap;

/**

* @author cattle - 稻草鸟人

* @date 2020/4/12 下午3:30

*/

public class Java8BiConsumer3 {

public static void main(String[] args) {

HashMap map = new HashMap<>();

map.put(1, "Java");

map.put(2, "Kotlin");

map.put(3, "React");

map.put(4, "Python");

map.put(5, "Go");

map.forEach((k, v) -> System.out.println(k + ":" + v));

}

}

输出:

1:Java

2:Kotlin

3:React

4:Python

5:Go

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值