You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java泛型重构两个逻辑相同的Stream处理方法?

泛型方法重构指导

你有两个逻辑完全一致的方法,分别处理Object1和Object2类型的列表,现在可以通过泛型方法将它们合并为一个通用实现,以下是具体步骤和代码:

现有代码

public static List<Long> function1(List<Object1> object1) {
    return object1.stream().map(Object1::getParameter1)
           .sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}
public static List<Long> function2(List<Object2> object2) {
    return object2.stream().map(Object2::getParameter1)
           .sorted(Comparator.reverseOrder()).collect(Collectors.toList());
}

通用泛型方法实现

注意:原方法的返回值是List<Long>(因为提取的参数是Long类型),所以泛型方法的返回值不能是List<T>,而是List<Long>。我们需要传入一个函数式接口来指定如何从任意类型T中提取Long参数:

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

public static <T> List<Long> genericFunction(List<T> list, Function<T, Long> parameterExtractor) {
    return list.stream()
            .map(parameterExtractor) // 用传入的函数提取Long类型参数
            .sorted(Comparator.reverseOrder()) // 对Long类型倒序排序,类型推断自动生效
            .collect(Collectors.toList());
}

调用示例

  • 替代原function1:
List<Long> result1 = genericFunction(object1List, Object1::getParameter1);
  • 替代原function2:
List<Long> result2 = genericFunction(object2List, Object2::getParameter1);

关键说明

  • <T>是泛型类型参数,表示该方法可以处理任意类型的列表
  • Function<T, Long>是函数式接口,用来定义从T类型对象中提取Long参数的逻辑,直接用方法引用(Object1::getParameter1)传递即可
  • sorted(Comparator.reverseOrder())不需要额外泛型声明,因为map后流的元素类型是Long,Java会自动推断出Comparator的类型

内容的提问来源于stack exchange,提问作者Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:27:20