Function、Consumer的使用
废话不多说,直接上代码:
public class FunctionPageUtils {
FunctionPageUtils() {}
/**
* 自定义函数:参数*10
* 参数:Integer
* 返回:Integer
*/
private static Function<Integer,Integer> action = action -> action * 10;
/**
* 自定义函数:+1操作,无返回值
* 参数:Integer
*/
private static Consumer<Integer> consumer = consumer -> {
consumer+=1;
System.out.println(consumer);
};
public static void main(String[] args) {
Integer apply = action.apply(10);
System.out.println(apply);
consumer.accept(apply);
FunctionPageUtils.dealPageFunction(num->{
// 假设固定每次取10个值
return getData((num - 1) * 10, num * 10);
},t->{
// 这里可以做一些复杂操作
System.out.println(",,,"+t);
});
}
/**
* 制造一些假数据:模拟分页查数据库数据
* @param num 相当于页数
* @param pageSize 相当于分页大小
* @return
*/
private static List<String> getData(Integer num, Integer pageSize) {
List<String> list = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
list.add(i+",,,");
}
// 因为查的不是数据库,会出现下标越界情况
try {
return list.subList(num,pageSize);
}catch (Exception e) {
return null;
}
}
/**
* 分页获取和处理数据
* @param param 函数式参数:param是函数式返回的结果,类型是List<T>
* @param consumer 函数式参数
* @param <T>
*/
public static <T> void dealPageFunction(Function<Integer,List<T>> param, Consumer<T> consumer) {
Integer num = 1;
// 调用自定义函数,传参获取集合
List<T> result = param.apply(num);
while (true) {
if(result == null) {
break;
}
for (T t : result) {
if(t == null) {
continue;
}
consumer.accept(t);
}
num ++;
result = param.apply(num);
}
}
}