How to add a prefix for all List items effectively?

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

The following is the way I accomplish this by iterating over a list and then adding it. Is there any other better way to do this? Any one or two liners that can do the same things?

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 a LinkedList, as I use some methods of the LinkedList class, such as removeFirst .

I'm on Java 7 now.

+5
source share
2 answers

For a single liner, use Java 8 threads:

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

If you must create a LinkedList , you must use a different collector.

+7
source

Your implementation looks fine, but if you want something else, try the following:

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

Thus, you create a "virtual list" that actually contains no data, but calculates it on the fly.

+4
source

All Articles