将List <Type>转换为List <OtherType>

时间:2019-11-20 12:39:03

标签: java list collections add

假设我们有以下代码

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

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

        return result;
    }

但是,我们得到了不同的Type(ScreenType,HomeType,UserType),我不想重复相同的方法3次以上,并且我不能使用继承,因为它们是Providen模型。 (拱形设计素材)。

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

这不是适当的解决方案。

此外:

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

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

1 个答案:

答案 0 :(得分:1)

通过流,您可以映射列表的元素。

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

无法保证List是哪种类型,因此您可能需要使用new ArrayList<>()或类似的文字进行包装。

如果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的需要。评论中的@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;
}
相关问题