暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

将 "函数式编程" 封装成工具类, 不香吗?

有猿再见 2021-04-12
1251

前言

本篇是对 Java8 常用函数式方法封装的工具类
分享,相信大家在工作中都会使用到函数式编程,本文会结合封装方法和案例场景进行分享。若有不足之处,感谢指出。

Show the code for you

1. 快速映射集合

将对象集合的某个字段快速映射成另一个集合

public static <E, R> List<R> map(Collection<E> collection, Function<E, R> mapper) {
    return collection.stream().map(mapper).collect(toList());
}

案例
@Test
public void map() {
    List<Integer> numList = FunctionUtils.map(users, User::getUserNum);
    System.out.println(numList);
    
    // 转换为数组
    Integer[] nums = numList.toArray(new Integer[0]);
    System.out.println(Arrays.asList(nums));
}

2. 自定义条件过滤出对象

使用场景:遍历一个集合 (users),根据该集合的数据从另一个集合 (orders) 获取数据

public static <E> Function<Predicate<E>, Optional<E>> filterOutObject(Collection<E> collection) {
    return predicate -> collection.stream().filter(predicate).findFirst();
}

案例
@Test
public void filterOutObject() {
    // 根据条件获取 user,这样的写法有点大材小用了
    Function<Predicate<User>, Optional<User>> predicateFunc = FunctionUtils.filterOutObject(users);
    Optional<User> user = predicateFunc.apply(u -> Objects.equals(u.getUserNum(), 1));
    user.ifPresent(System.out::println);

    // 更适合的案例场景: 获取 order 对应的 user 信息
    orders.forEach(order -> {
        Optional<User> userOpt = predicateFunc.apply(u -> Objects.equals(u.getUserNum(), order.getUserNum()));
        userOpt.ifPresent(u -> System.out.println(String.format("order id: %s, username: %s", order.getOrderId(), u.getUsername())));
    });
}

3. 分组

分组与快速映射集合
 一样的思路

public static <E, K> Map<K, List<E>> groupBy(Collection<E> collection, Function<E, K> mapper) {
    return collection.stream().collect(Collectors.groupingBy(mapper));
}

案例
@Test
public void groupBy() {
    Map<Integer, List<Order>> userOrders = FunctionUtils.groupBy(orders, Order::getUserNum);
    userOrders.forEach((key, value) -> System.out.println(key + " -> " + value));
}

4. Map 排序

其原理就是根据 Key 排序,将数据再使用 LinkedHashMap 装载。因为这里使用的是泛型,所以 sorted 方法将 Key 进行了 toString() 操作, 正常调用该方法这样写即可: .sorted(Map.Entry.comparingByKey())

public static <K, V> LinkedHashMap<K, V> sortMap(Map<K, V> map) {
    return map.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByKey(Comparator.comparing(Object::toString)))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    right(),
                    LinkedHashMap::new));

}

案例

以订单日期分组进行分组排序

@Test
public void sortMap() {
    // Case 1
    Map<LocalDate, List<Order>> map = FunctionUtils.groupBy(orders, Order::getCreatedDateTime);
    LinkedHashMap<LocalDate, List<Order>> sortMap1 = FunctionUtils.sortMap(map);
    sortMap1.forEach((key, value) -> System.out.println(key + " -> " + value));

    // Case 2
    LinkedHashMap<LocalDate, List<Order>> sortMap2 = FunctionUtils.sortMap(orders, Order::getCreatedDateTime);
    sortMap2.forEach((key, value) -> System.out.println(key + " -> " + value));
}

结尾

本文简单的分享了几个常用的案例,希望对大家有所帮助。源码案例更丰富:  点击阅读原文。后续会持续更新该文章

文章转载自有猿再见,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论