Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 638
user1950349 Avatar asked May 18 '15 06:05

user1950349


People also ask

How many elements can you store in a list?

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.


2 Answers

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.

like image 117
Eran Avatar answered Sep 30 '22 01:09

Eran


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.

like image 23
Tagir Valeev Avatar answered Sep 30 '22 01:09

Tagir Valeev