对Java 8 的使用心得
1. 函数接口类
- consumer函数(消费函数): 有参数无返回值
public class consumerInterface {
public static void main(String[] args) {
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("hello wold!");
}
}
在Java8 中实现消费型函数,如上代码,抽象接口的实现部分为System.out.println(s);调用抽象方法的accept 方法来传递参数值。
- supplier 函数(供给型函数): 无参数有返回值
练习需求: 产生指定个数的数据,数据类型使用supplier 函数实现
public static void main(String[] args) {
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept("hello wold!");
/**
* Math.random 函数产生的 值在0.0 - 1.0 之间
* 需求: 产生指定数量,指定范围的 整数值
*/
consumerInterface intance = new consumerInterface();
List<Integer> list = intance.getList(10,() -> (int)(Math.random() * 100));
for (Integer i: list ) {
System.out.println(i);
}
}
public List<Integer> getList (int len, Supplier<Integer> sup ){
List<Integer> list = new ArrayList<>();
for (int i = 0; i < len ; i++) {
list.add(sup.get());
}
return list;
}
- predicate 函数(断言型函数): 有参数又返回值,返回值为true 或者 false
需求: 将满足条件的字段串,放入集合中
List<String> stringList = intance.predicateStr("AAAaaaaa",(string) ->{
if(string.length() > 5){
return true;
}else {
return false;
}
});
stringList.forEach(e -> System.out.println(e.toString()));
public List<String> predicateStr(String source , Predicate<String> predicate){
List<String> list = new ArrayList<>();
boolean flag = predicate.test(source);
if(flag){
list.add(source);
}
return list;
}
- function 函数(函数型函数):有参数有返回值
练习需求:用于处理字符串,字符串的处理方式由函数 function 接口的实现 来指定
/**
* 将给定的字符串,提取其中的字符
*/
List<String> arrayChar = intance.handleStr("AAAABBBBCCC",(str) ->{
List<String> newChars = new ArrayList<>();
char[] chars = str.toCharArray();
for (char c : chars) {
/**
* contains() 循环调用对象的equal() 方法
*/
if(!newChars.contains(c)){
newChars.add(String.valueOf(c));
}
}
return newChars;
});
public List<String> handleStr(String source, Function<String, List<String>> function){
return function.apply(source);
}
4034

被折叠的 条评论
为什么被折叠?



