java8里面consumer&BiConsumer也是函数式接口,从代码上看,consumer只有一个入参,没有返回值;BiConsumer两个入参,没有返回值。
1、Consumer简单例子
1package com.cattles.function; 2 3import java.util.function.Consumer; 4 5/** 6 * @author cattle - 稻草鸟人 7 * @date 2020/4/12 下午3:04 8 */ 9public class Java8Consumer1 { 10 11 public static void main(String[] args) { 12 Consumer<String> stringConsumer = x -> System.out.println("hello!" + x); 13 stringConsumer.accept("cattle"); 14 } 15} 16
输出:
hello!cattle
2、Consumer当做参数传输
1package com.cattles.function; 2 3import java.util.Arrays; 4import java.util.List; 5import java.util.function.Consumer; 6 7/** 8 * @author cattle - 稻草鸟人 9 * @date 2020/4/12 下午3:13 10 */ 11public class Java8Consumer2 { 12 13 public static void main(String[] args) { 14 List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); 15 Consumer<Integer> integerConsumer = x -> System.out.println(x); 16 forEach(integers, integerConsumer); 17 System.out.println("==========="); 18 forEach(integers, x -> System.out.println(x)); 19 } 20 21 static <T> void forEach(List<T> list, Consumer<T> consumer) { 22 list.forEach(consumer); 23 } 24} 25
输出:
11 22 33 44 55 66 77 88 9=========== 101 112 123 134 145 156 167 178 18
3、BiConsumer简单例子
1package com.cattles.function; 2 3import java.util.function.BiConsumer; 4 5/** 6 * @author cattle - 稻草鸟人 7 * @date 2020/4/12 下午3:20 8 */ 9public class Java8BiConsumer1 { 10 public static void main(String[] args) { 11 BiConsumer<Integer, Integer> add = (x, y) -> System.out.println(Math.addExact(x, y)); 12 add.accept(1, 2); 13 } 14} 15
输出
3
4、BiConsumer当做参数传输
1package com.cattles.function; 2 3import java.util.function.BiConsumer; 4 5/** 6 * @author cattle - 稻草鸟人 7 * @date 2020/4/12 下午3:23 8 */ 9public class Java8BiConsumer2 { 10 11 public static void main(String[] args) { 12 add(1, 2, (x, y) -> System.out.println(x + y)); 13 add("Hello!", "Cattle", (x, y) -> System.out.println(x + y)); 14 } 15 16 static <T> void add(T a, T b, BiConsumer<T, T> c) { 17 c.accept(a, b); 18 } 19} 20
输出:
13 2Hello!Cattle
5、Map.forEach例子
在第2点,consumer当做参数例子里面,我们发现list的forEach代码参数是Consumer,而map里面的forEach参数则使用的是BiConsumer,下面我们看下例子
1package com.cattles.function; 2 3import java.util.HashMap; 4 5/** 6 * @author cattle - 稻草鸟人 7 * @date 2020/4/12 下午3:30 8 */ 9public class Java8BiConsumer3 { 10 11 public static void main(String[] args) { 12 HashMap<Integer, String> map = new HashMap<>(); 13 map.put(1, "Java"); 14 map.put(2, "Kotlin"); 15 map.put(3, "React"); 16 map.put(4, "Python"); 17 map.put(5, "Go"); 18 map.forEach((k, v) -> System.out.println(k + ":" + v)); 19 } 20} 21
输出:
11:Java 22:Kotlin 33:React 44:Python 55:Go