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<String> 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<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
Consumer<Integer> integerConsumer = x -> System.out.println(x);
forEach(integers, integerConsumer);
System.out.println("===========");
forEach(integers, x -> System.out.println(x));
}
static <T> void forEach(List<T> list, Consumer<T> 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<Integer, Integer> 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 <T> void add(T a, T b, BiConsumer<T, T> 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<Integer, String> 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