之前其实写过Java8新特性的函数式接口的文章,现在再一次重复,之前学过的内容,偏重于笔记,在工作中的使用场景并不是很多,再一次总结,除了温故而知新,也结合一些自己工作中遇到的案例,希望可以帮助到需要的朋友。
1、消费型接口,有入参,没有返回值
通常用于对入参的逻辑处理,简化重复定义方法的流程,优化代码简洁度。
@FunctionalInterface
public interface Consumer<T> {
/**
* Performs this operation on the given argument.
*
* @param t the input argument
*/
void accept(T t);
/**
* Returns a composed {@code Consumer} that performs, in sequence, this
* operation followed by the {@code after} operation. If performing either
* operation throws an exception, it is relayed to the caller of the
* composed operation. If performing this operation throws an exception,
* the {@code after} operation will not be performed.
*
* @param after the operation to perform after this operation
* @return a composed {@code Consumer} that performs in sequence this
* operation followed by the {@code after} operation
* @throws NullPointerException if {@code after} is null
*/
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after);
return (T t) -> { accept(t); after.accept(t); };
}
}
你如果需要访问类型T的对象,并对其执行某些操作,就可以使用这个接口。而且此接口还有默认方法andThen,用于拼接多个Consumer对象的执行内容。按拼接顺序从前往后依次执行
@Test
public void test() {
happy(1000, x -> System.out.println(x));
}
private void happy(Integer money, Consumer<Integer> consumer) {
consumer.accept(money);
consumer.andThen(x -> System.out.println(x / 2)).accept(money);
}
2、供给型接口,没有入参,只有返回值
它接受一个泛型T的对象,并返回这个泛型T的对象
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
eg 生成10个数字,作为list返回
public List<Integer> getList(int num, Supplier<Integer> supplier) {
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < num; i++) {
list.add(supplier.get());
}
return list;
}
@Test
public void test() {
List<Integer> list = getList(10, () -> (int) (Math.random() * 100));
System.out.println(list);
}
3、函数型接口,一个参数,有返回值
它接受一个泛型T的对象,并返回一个泛型R的对象,将输入对象的信息映射到输出,可以使用此接口。
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
public String strHandler(Integer x, Function<Integer, String> function) {
return function.apply(x);
}
@Test
public void test1() {
String handler = strHandler(1, x -> "我有" + x + "个朋友");
System.out.println(handler);
}
举个工作中简化代码的逻辑
优化前
//只有输入参数不同,其他的都是重复逻辑
//呼入总量
Map<String, Long> callCityMap = callList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
//呼入有效咨询量
Map<String, Long> callValidCityMap = callValidList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
//呼入分配量
Map<String, Long> callAppointCityMap = callAppointList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
//在线咨询
Map<String, Long> onlineCityMap = onlineList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
优化之后
private Map<String,Long> getWorkCount(List<WorkOrder> workOrders,Function<List<WorkOrder>, Map<String, Long>> function){
return function.apply(workOrders);
}
Function<List<WorkOrder>, Map<String, Long>> function = workOrders -> workOrders.stream().collect(Collectors.groupingBy(WorkOrder::getSeatCode, Collectors.counting()));
Map<String, Long> callCityMap =getWorkCount(callList,function);
Map<String, Long> callSeatMap =getWorkCount(callSeatList,function);
4、断言型接口 有参数,返回值为boolean
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
举例说明 对字符串的过滤可以进行筛选
@Test
public void test2() {
boolean result = judgeLength("iiiiii", s -> s.length() > 2);
System.out.println(result);
}
public boolean judgeLength(String s, Predicate<String> predicate) {
return predicate.test(s);
}
举个工作中简化代码的逻辑
//只有filter中内容不一样
List<WorkOrder> callList = workOrderList.stream()
.filter(workOrder -> workOrder.getActivityType() == EActivityType.CALL.getValue())
.collect(Collectors.toList());
List<WorkOrder> callValidList = workOrderList.stream()
.filter(workOrder -> workOrder.getActivityType() == EActivityType.CALL.getValue()
&& resourceType.contains(workOrder.getServiceCode()))
.collect(Collectors.toList());
List<WorkOrder> callAppointList = workOrderList.stream()
.filter(workOrder -> workOrder.getChannelType() != null && workOrder.getChannelType() == EActivityType.CALL.getValue()
&& workOrder.getAppointResult() != null && workOrder.getAppointResult() == EAppointResult.ADVISER.getValue())
.collect(Collectors.toList());
List<WorkOrder> onlineList = workOrderList.stream()
.filter(workOrder -> workOrder.getActivityType() == EActivityType.ONLINE.getValue())
.collect(Collectors.toList());
优化后,将过滤部分利用断言接口抽象,减少冗余代码
private List<WorkOrder> getWorkList(List<WorkOrder> workOrderList, Predicate<WorkOrder> call) {
List<WorkOrder> collect = workOrderList.stream().filter(call).collect(Collectors.toList());
return collect;
}
Predicate<WorkOrder> call = workOrder -> workOrder.getActivityType()== EActivityType.CALL.getValue();
List<WorkOrder> collect= getWorkList(workOrderList, call);
总结
java8带来的好处就是简化现在的冗余代码,但是很多知识学过后特别容易忘记,温故知新,遇到冗余的地方要想办法去解决,尽量将学习的内容在工作中得已实践。
岁月正好,吾辈还需更加努力。