Java Function<T, R> 接口

Function<T, R> 是 Java 8 引入的函数式接口,位于 java.util.function 包中,代表一个接受一个参数并返回结果的函数。

@FunctionalInterface
public interface Function<T, R> {
    R apply(T t);                    // 抽象方法:执行转换
    default <V> Function<V, R> compose(Function<? super V, ? extends T> before);
    default <V> Function<T, V> andThen(Function<? super R, ? extends V> after);
    static <T> Function<T, T> identity();
}
方法类型说明
apply(T t)抽象方法核心方法,接收 T 类型参数,返回 R 类型结果
compose()默认方法先执行传入的函数,再执行当前函数
andThen()默认方法先执行当前函数,再执行传入的函数
identity()静态方法返回一个"输入是什么就返回什么"的函数

apply() — 核心方法

Function<String, Integer> func = s -> s.length();
Integer len = func.apply("hello"); // 5

常见使用场景

Stream 中的 map()

List<String> names = users.stream()
    .map(User::getName)  // Function<User, String>
    .collect(Collectors.toList());

PO → VO 转换

Function<UserPO, UserVO> converter = po -> {
    UserVO vo = new UserVO();
    vo.setName(po.getName());
    vo.setAge(po.getAge());
    return vo;
};
UserVO vo = converter.apply(po);

封装

package com.purvar.ezgo.framework.wrapper;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 视图包装类
 */
public class EntityWrapper {
    /**
     * 单个实体类包装
     *
     * @param entity 实体类
     * @return V
     */
    public static <PO, VO> VO entityVO(PO entity, Function<? super PO, ? extends VO> mapper) {
        return mapper.apply(entity);
    }

    public static <PO, VO> List<VO> listVO(List<PO> list, Function<? super PO, ? extends VO> mapper) {
        return list.stream().map(mapper).collect(Collectors.toList());
    }

    /**
     * 分页实体类集合包装
     *
     * @param pages 分页对象
     * @return IPage<V>
     */
    public static <PO, VO> List<VO> listVO(IPage<PO> pages, Function<? super PO, ? extends VO> mapper) {
        List<VO> records = listVO(pages.getRecords(), mapper);
        return records;
    }

    /**
     * 分页实体类集合包装
     *
     * @param pages 分页对象
     * @return IPage<V>
     */
    public static <PO, VO> IPage<VO> pageVO(IPage<PO> pages, Function<? super PO, ? extends VO> mapper) {
        List<VO> records = listVO(pages.getRecords(), mapper);
        IPage pageVo = new Page<>(pages.getCurrent(), pages.getSize(), pages.getTotal());
        pageVo.setRecords(records);
        return pageVo;
    }
}

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐