Java8 4大函数接口
最近在学习Java8新特性,看到了lambda 表达式的强大 ,通过几个简单实例演示4大核心函数接口的使用!
/**
* Predicate 断言型接口
* 获取长度大于4的数据
*/
@Test
public void testPredicate() {
preStr(Arrays.asList("zhangsan", "lisi", "wangwu"), x -> x.length() > 4)
.forEach(x -> System.out.println(x));
}
public List preStr(List<String> listStr, Predicate<String> predicate) {
List<String> list = new ArrayList<>();
for (String str : listStr) {
if (predicate.test(str)) {
list.add(str);
}
}
return list;
}
输出结果:
zhangsan
wangwu
/**
* Supplier 供给型接口
* 输出9个 两位随机数
*/
@Test
public void testSupplier() {
List<Integer> listNum = supplier(9, () -> (int) (Math.random() * 100));
listNum.forEach(x -> System.out.println(x));
}
public List<Integer> supplier(int num, Supplier<Integer> supplier) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < num; i++) {
list.add(supplier.get());
}
return list;
}
输出结果:
17
35
33
40
7
86
93
58
53
/**
* Function 函数型接口
* 根据 , ; 把字符串进行分割
*/
@Test
public void testFunction() {
String str = "a,b,c";
List list = getStrArray(str, x -> Arrays.asList(x.split(",")));
list.forEach(a -> System.out.println(a));
System.out.println("---------------------");
str = "d;e;f";
list = getStrArray(str, x -> Arrays.asList(x.split(";")));
list.forEach(a -> System.out.println(a));
}
public List getStrArray(String str, Function<String, List> function) {
return function.apply(str);
}
输出结果:
a
b
c
---------------------
d
e
f
/**
* Consumer 消费型接口
* 传递一个参数 进行消费输出
*/
@Test
public void testConsumer() {
consumer(20.00, x -> System.out.println("今天购物消费" + x));
}
public void consumer(Double money, Consumer<Double> consumer) {
consumer.accept(money);
}
输出结果:
今天购物消费20.0