之前其实写过Java8新特性的函数式接口的文章,现在再一次重复,之前学过的内容,偏重于笔记,在工作中的使用场景并不是很多,再一次总结,除了温故而知新,也结合一些自己工作中遇到的案例,希望可以帮助到需要的朋友。
通常用于对入参的逻辑处理,简化重复定义方法的流程,优化代码简洁度。
@FunctionalInterface
public interface Consumer {
/**
* 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 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 consumer) {
consumer.accept(money);
consumer.andThen(x -> System.out.println(x / 2)).accept(money);
}
它接受一个泛型T的对象,并返回这个泛型T的对象
@FunctionalInterface
public interface Supplier {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
eg 生成10个数字,作为list返回
public List getList(int num, Supplier supplier) {
List list = Lists.newArrayList();
for (int i = 0; i < num; i++) {
list.add(supplier.get());
}
return list;
}
@Test
public void test() {
List list = getList(10, () -> (int) (Math.random() * 100));
System.out.println(list);
}
它接受一个泛型T的对象,并返回一个泛型R的对象,将输入对象的信息映射到输出,可以使用此接口。
@FunctionalInterface
public interface Function {
/**
* 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 function) {
return function.apply(x);
}
@Test
public void test1() {
String handler = strHandler(1, x -> "我有" + x + "个朋友");
System.out.println(handler);
}
举个工作中简化代码的逻辑
优化前
//只有输入参数不同,其他的都是重复逻辑
//呼入总量
Map callCityMap = callList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
//呼入有效咨询量
Map callValidCityMap = callValidList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
//呼入分配量
Map callAppointCityMap = callAppointList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
//在线咨询
Map onlineCityMap = onlineList.stream()
.collect(Collectors.groupingBy(WorkOrder::getCity, Collectors.counting()));
优化之后
private Map getWorkCount(List workOrders,Function, Map> function){
return function.apply(workOrders);
}
Function, Map> function = workOrders -> workOrders.stream().collect(Collectors.groupingBy(WorkOrder::getSeatCode, Collectors.counting()));
Map callCityMap =getWorkCount(callList,function);
Map callSeatMap =getWorkCount(callSeatList,function);
@FunctionalInterface
public interface Predicate {
/**
* 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 predicate) {
return predicate.test(s);
}
举个工作中简化代码的逻辑
//只有filter中内容不一样
List callList = workOrderList.stream()
.filter(workOrder -> workOrder.getActivityType() == EActivityType.CALL.getValue())
.collect(Collectors.toList());
List callValidList = workOrderList.stream()
.filter(workOrder -> workOrder.getActivityType() == EActivityType.CALL.getValue()
&& resourceType.contains(workOrder.getServiceCode()))
.collect(Collectors.toList());
List 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 onlineList = workOrderList.stream()
.filter(workOrder -> workOrder.getActivityType() == EActivityType.ONLINE.getValue())
.collect(Collectors.toList());
优化后,将过滤部分利用断言接口抽象,减少冗余代码
private List getWorkList(List workOrderList, Predicate call) {
List collect = workOrderList.stream().filter(call).collect(Collectors.toList());
return collect;
}
Predicate call = workOrder -> workOrder.getActivityType()== EActivityType.CALL.getValue();
List collect= getWorkList(workOrderList, call);
java8带来的好处就是简化现在的冗余代码,但是很多知识学过后特别容易忘记,温故知新,遇到冗余的地方要想办法去解决,尽量将学习的内容在工作中得已实践。
岁月正好,吾辈还需更加努力。