Array to Collection: Optimized code

JavaArraysCollections

Java Problem Overview


Is there a better way of achieving this?

public static List<String> toList(String[] array) {

	List<String> list = new ArrayList(array.length);

	for(int i=0; i<array.length; i++)
		list.add(array[i]);

	return list;
}

NOTE: Arrays.asList(a) Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.). I don't want that behavior. I assume that MY function above bypasses that (or am I wrong?)

So, here we have the alternative method:

public static List<String> toList(String[] array) {

	List<String> list = new ArrayList(array.length);

	list.addAll(Arrays.asList(array));

	return list;
}

Just looking at it, I don't believe it's FASTER than the first method.

Java Solutions


Solution 1 - Java

What do you mean by better way:

more readable:

List<String> list = new ArrayList<String>(Arrays.asList(array));

less memory consumption, and maybe faster (but definitely not thread safe):

public static List<String> toList(String[] array) {
    if (array==null) {
       return new ArrayList(0);
    } else {
       int size = array.length;
       List<String> list = new ArrayList(size);
       for(int i = 0; i < size; i++) {
          list.add(array[i]);
       }
       return list;
    }
}

Btw: here is a bug in your first example:

array.length will raise a null pointer exception if array is null, so the check if (array!=null) must be done first.

Solution 2 - Java

Arrays.asList(array);    

Example:

 List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");

See Arrays.asList class documentation.

Solution 3 - Java

Arrays.asList(array)

Arrays uses new ArrayList(array). But this is not the java.util.ArrayList. It's very similar though. Note that this constructor takes the array and places it as the backing array of the list. So it is O(1).

In case you already have the list created, Collections.addAll(list, array), but that's less efficient.

Update: Thus your Collections.addAll(list, array) becomes a good option. A wrapper of it is guava's Lists.newArrayList(array).

Solution 4 - Java

Another way to do it:

Collections.addAll(collectionInstance,array);

Solution 5 - Java

What about :

List myList = new ArrayList(); 
String[] myStringArray = new String[] {"Java", "is", "Cool"}; 

Collections.addAll(myList, myStringArray); 

Solution 6 - Java

You can use:

list.addAll(Arrays.asList(array));

Solution 7 - Java

You can try something like this:

List<String> list = new ArrayList<String>(Arrays.asList(array));

> public ArrayList(Collection c)

> Constructs a list containing the > elements of the specified collection, > in the order they are returned by the > collection's iterator. The ArrayList > instance has an initial capacity of > 110% the size of the specified > collection.

Taken from here

Solution 8 - Java

Based on the reference of java.util.Collections.addAll(Collection<? super String> c, String... elements) its implementation is similar to your first method, it says

> Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

Its implementation in jdk is (jdk7)

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
    boolean result = false;
    for (T element : elements)
        result |= c.add(element);
    return result;
}

So among your samples the better approach must be Collections.addAll(list, array);

Since Java 8, we can use Stream api which may perform better

Eg:-

String[] array = {"item1", "item2", "item3"};

Stream<String> stream = Stream.of(array);

//if the array is extremely large 
stream = stream.parallel();

final List<String> list = stream.collect(Collectors.toList());

If the array is very large we can do it as a batch operation in parallel using parallel stream (stream = stream.parallel()) that will utilize all CPUs to finish the task quickly. If the array length is very small parallel stream will take more time than sequential stream.

Solution 9 - Java

Have you checked Arrays.asList(); see API

Solution 10 - Java

Yes, there is. You can use the Arrays class from the java.util.* package. Then it's actually just one line of code.

List<String> list = Arrays.asList(array);

Solution 11 - Java

You can use List.of(array) to get an immutable list.

https://docs.oracle.com/en/java/javase/16/core/creating-immutable-lists-sets-and-maps.html#GUID-202D195E-6E18-41F6-90C0-7423B2C9B381

edit 2021-05-01 @Rup: To get a mutable list you could use

var list = new ArrayList<String>(List.of(array));

edit 2021-05-04: It might be faster to use

var list = new ArrayList<String>(Arrays.asList(array));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmarcolopesView Question on Stackoverflow
Solution 1 - JavaRalphView Answer on Stackoverflow
Solution 2 - JavajmjView Answer on Stackoverflow
Solution 3 - JavaBozhoView Answer on Stackoverflow
Solution 4 - JavadiegoehgView Answer on Stackoverflow
Solution 5 - JavaantView Answer on Stackoverflow
Solution 6 - JavaMohamed SalighView Answer on Stackoverflow
Solution 7 - JavanpintiView Answer on Stackoverflow
Solution 8 - JavaVisruthView Answer on Stackoverflow
Solution 9 - JavaposdefView Answer on Stackoverflow
Solution 10 - JavaMarioB.View Answer on Stackoverflow
Solution 11 - JavarichardView Answer on Stackoverflow