How to add prefix to all the elements of List efficiently?

丶灬走出姿态 提交于 2021-02-05 05:07:30

问题


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

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

I am on Java 7 as of now.


回答1:


For one liners, use Java 8 Streams :

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

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




回答2:


Your implementation looks ok, but if you want something different, try this:

public static List<String> getData(final TypeFlow flow) {
    return new AbstractList<String>() {
        @Override
        public String get(int index) {
            return flow.value()+DATA_TYPE.get(index).value();
        }

        @Override
        public int size() {
            return DATA_TYPE.size();
        }
    };
}

This way you create a "virtual list" which does not actually contains data, but computes it on the fly.



来源:https://stackoverflow.com/questions/30296786/how-to-add-prefix-to-all-the-elements-of-list-efficiently

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!