问题
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