如何有效地为List的所有元素添加前缀?

use*_*349 5 java collections list set

我有一个List,我需要在列表的所有元素中添加前缀.

下面是我通过迭代列表然后添加它的方式.还有其他更好的方法吗?任何一两个衬垫可以做同样的东西?

private static final List<DataType> DATA_TYPE = getTypes();

public static LinkedList<String> getData(TypeFlow flow) {
    LinkedList<String> paths = new LinkedList<String>();
    for (DataType current : DATA_TYPE) {
        paths.add(flow.value() + current.value());
    }
    return paths;
}
Run Code Online (Sandbox Code Playgroud)

我需要返回LinkedList,因为我使用的是LinkedList类的一些方法removeFirst.

我现在在Java 7上.

Era*_*ran 7

对于一个衬垫,使用Java 8 Streams:

List<String> paths = DATA_TYPE.stream().map(c -> flow.value() + c.value()).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

如果必须生成a LinkedList,则应使用其他收集器.

  • @ user1950349在Java 7中,您的实现看起来尽可能短. (2认同)