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) Yes, list can store 100000+ elements. The maximum capacity of an List is limited only by the amount of memory the JVM has available. 2) For performance issues, it depends on the type of data to be stored. Normaly HashMaps are used for databases.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With