【问题标题】:Fastest way to convert a List<Type> to List<OtherType>将 List<Type> 转换为 List<OtherType> 的最快方法
【发布时间】:2019-11-20 12:39:03
【问题描述】:

假设我们有以下代码

private List<String> convertScreenTypeToString(List<ScreenType> screenTypeList){
        List<String> result = new ArrayList<>();

        for(ScreenType screenType : screenTypeList){
            result.add(screenType.getLabel());
        }

        return result;
    }

但是,我们得到了不同的类型(ScreenType、HomeType、UserType),我不想重复同样的方法 3 次,而且我不能使用继承,因为它们是提供的模型。 (建筑设计的东西)。

还有,

.... TypeToScreen(List<Object> whatever){}

这不是一个合适的解决方案。

此外:

private class Convert<T>{ .....TypeToScreen(List<T> whatecer){}}

在父类里面是可以的,但我正在寻找一些高级方法

【问题讨论】:

  • 标题:“隐蔽”还是“转换”?
  • 转换** Jajajaja 我错过了 n。哪里可以改?
  • 在标题中?!您的浏览器不能进行字符串搜索吗? ;-)

标签: java list collections add


【解决方案1】:

Streams 可以让您映射列表的元素。

List<String> labels =
    screenTypes.stream()
        .map(ScreenType::getLabel)
        .collect(Collectors.toList());

无法保证List 是哪种类型,因此您可能需要使用new ArrayList&lt;&gt;() 或类似名称进行包装。

如果List上有这样的方法就方便了。您可以为这种非常常见的情况编写一个方便的方法。

public static <T, R> List<R> map(
    List<T> source, Function<? super T,​ ? extends R> mapping
) {
    return
        screenTypes.stream()
            .map(mapping)
            .collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
}

这里Stream.collect 的三参数形式消除了对中间List 的需要。 cmets 中的@Ousmane D. 提供了替代的最后一行。

            .collect(Collectors.toCollection(ArrayList::new));

或者,您可以在没有流的情况下将其写出来。如果其中任何一个对您来说很重要,这将更快、更容易阅读。

public static <T, R> List<R> map(
    List<T> source, Function<? super T,​ ? extends R> mapping
) {
    List<R> result = new ArrayList<>(source.size());
    for (T t : source) {
        result.add(mapping.apply(t));
    }
    return result;
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-02-17
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-02
相关资源
最近更新 更多