如何有效地为List的所有元素添加前缀? [英] How to add prefix to all the elements of List efficiently?

查看:250
本文介绍了如何有效地为List的所有元素添加前缀?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a List in which I need to add a prefix in all the elements of my list.

下面是通过迭代列表然后添加列表的方式.还有其他更好的方法吗?能做同样事情的任何一两个班轮吗?

Below is the way I am doing it by iterating the list and then adding it. Is there any other better way to do it? Any one-two liner that can do the same stuff?

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;
}

我需要返回LinkedList,因为我正在使用LinkedList类的某些方法,例如 removeFirst .

I need to return LinkedList since I am using some methods of LinkedList class like removeFirst.

到目前为止,我使用的是Java 7.

I am on Java 7 as of now.

推荐答案

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

For one liners, use Java 8 Streams :

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

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

If you must produce a LinkedList, you should use a different Collector.

这篇关于如何有效地为List的所有元素添加前缀?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆