Can we convert arraylist to array in java

Convert a List to Array and back in Java

Learn to convert a list to an array in Java and also convert a given array to a list. We will learn the conversions using the core Java APIs.

  • In Java, Lists are index-based ordered collections that provide random access to the elements by their integer index location.
  • Arrays are also similar to lists but are stored in contiguous memory. This is the reason that resizing the arrays is an expensive operation.

1. Converting List to Array

We can use the following two approaches to convert a given list to an array.

Using list.toArray() is the most straightforward way for the list-to-array conversion. It is an overloaded function.

  • Object[] toArray() : returns an array containing all of the elements in the list.
  • T[] toArray(T[] a) : returns an array containing all of the elements in the list, and the type of the returned array is that of the specified array a.
    If the collection fits in the specified array, it is returned therein. Otherwise, a new array is allocated of the size of the given list. If the specified array is bigger than the list then spare indices are filled with null .
  • default T[] toArray(IntFunction generator) : returns an array containing all of the elements in the list and the provided generator function is used to allocate the returned array.

Let’s see some examples of these methods.

List list = Arrays.asList("A", "B", "C"); String[] stringArray; //1 Object[] objArray = list.toArray(); //2 stringArray = list.toArray(new String[0]); //3 stringArray = list.toArray(String[]::new);

The stream.toArray() method is similar to the list.toArray() method discussed above. It is also an overloaded method.

  • Object[] toArray() : returns an array containing the elements of the stream obtained from the list.
  • A[] toArray(IntFunction generator) : returns an array containing the elements of the stream obtained from the list and the generator function used to allocate the returned array.
List list = Arrays.asList("A", "B", "C"); String[] stringArray = list.stream().toArray(String[]::new);

The benefits of using the streams are as follows:

  • We can use the list.parallelStream() if the list size is considerably bigger to be processed in a single thread. Parallel streams enable us to execute code in parallel on separate cores. However, the order of execution is out of our control so the items in the array will not be in the same order as in the list.
  • Another advantage is that we can apply intermediate stream operations such as filter() if we need to fill only selected items from the list.

For example, in the given code, we do want to fill the array with the list items only starting with the character ‘ A ‘.

String[] filteredArray = list.stream() .filter(s -> s.equals("A")) .toArray(String[]::new);

2. Converting Array to List

Converting an array to a list in Java is a rather simple job. We need to use the Arrays.asList() API. Note that the returned list is a fixed-size list backed by the given array. Changes made to the array will be visible in the returned list, and changes made to the list will be visible in the array.

String[] stringArray = new String[]; List list = Arrays.asList(stringArray);

Any method invoked on the list that can change its size will throw UnsupportedOperationException. Still, we can modify the objects stored in the list.

//changes the list and the array list.set(0, "Aa"); //Both array and the list are changed System.out.println(list); //[Aa, B, C] System.out.println(Arrays.toString(stringArray)); //[Aa, B, C] list.add("D"); //java.lang.UnsupportedOperationException

2.2. Using Collections.unmodifiableList()

To create an unmodifiable list, we should use Collections.unmodifiableList() API.

String[] stringArray = new String[]; List list = Collections.unmodifiableList(Arrays.asList(stringArray)); //Cannot change the list list.set(0, "Aa"); //java.lang.UnsupportedOperationException

2.3. Using Iteration and Stream

To create a new mutable list, independent of the array, we can use the stream API to iterate over the array and populate the list one item at a time.

String[] stringArray = new String[]; List list = Stream.of(stringArray).collect(Collectors.toList());

The created list is totally separate from the array, and both change independently.

//changes the list but NOT the array list.add("D"); //List has been updated but the array is unchanged System.out.println(list); //[A, B, C, D] System.out.println(Arrays.toString(stringArray)); //[A, B, C]

In this short tutorial, we learned to convert a list (e.g. ArrayList) to an array using the list.toArray() and stream.toArray() methods. Similarly, we learned to get the list from an array using the Arrays.asList() method.

There are a few other ways, for example, using Apache Commons and Guava APIs, but it is overkill to do this simple job without any clear benefit.

Источник

ArrayList to Array Conversion in Java

ArrayList is a resizable List implementation backed by an array. In other words, it implements the List interface and uses an array internally to support list operations such as add, remove, etc.

To convert ArrayList to array in Java, we can use the toArray(T[] a) method of the ArrayList class. It will return an array containing all of the elements in this list in the proper order (from first to last element.)

Here’s a short example to convert an ArrayList of integers, numbersList , to int array.

Integer[] array = numbersList.toArray(new Integer[0]); 

Replace Integer with the type of ArrayList you’re trying to convert to array and it’ll work E.g. for String :

String[] array = strList.toArray(new String[0]); 

What’s with the weird-looking argument new Integer[0] ? The reason it is there because the type of returned array is determined using this argument. In other words, the toArray(. ) method uses the type of the argument, Integer to create another array of the same type, places all elements from ArrayList into the array in order and returns it.

There is something else about the behavior of toArray(. ) method you must understand. Notice that we passed an empty array new Integer[0] . This was intentional because if we pass a non-empty array and it has enough room to fit all elements, ArrayList will use this array instead of creating a new one. So by passing an empty array (size 0), we’re forcing ArrayList to create a new array and return it. The returned array is not connected to ArrayList in any way, but keep in mind that it is a shallow copy of the elements of the ArrayList.

Examples

Now let’s take a look at some examples.

1. Covert ArrayList of integers to int array

In other words, ArrayList to Integer[].

package com.codeahoy.ex; import java.util.ArrayList; import java.util.List; public class Main  public static void main(String[] args)  ListInteger> list = new ArrayList<>(); // Add elements to the list list.add(5); list.add(10); list.add(15); // Convert ArrayList to Array Integer[] array = list.toArray(new Integer[0]); // Print the array for (Integer n : array)  System.out.println(n); > > > 

2. Covert ArrayList of strings to String array

That is, ArrayList to String[]

package com.codeahoy.ex; import java.util.ArrayList; import java.util.List; public class Main  public static void main(String[] args)  ListString> list = new ArrayList<>(); // Add elements to the list list.add("List"); list.add("Set"); list.add("HashMap"); // Convert ArrayList to Array String[] array = list.toArray(new String[0]); // Print the array for (String s : array)  System.out.println(s); > > > 

3. Alternate Way: The other toArray() method

There’s another method, toArray() which doesn’t take any arguments. It behavior is identical to its overloaded cousin described above, except that it returns an array of objects i.e. Object [] . If you use this method, you need to cast it manually.

Object[] array = list.toArray(); 

4. Convert ArrayList to Array Using Java 8 Streams

We can use the toArray() method of Streams API in Java 8 and above to convert ArrayList to array. I’m just putting it here for the sake of completeness. It requires converting ArrayList to a Stream first, which is unnecessary.

public static void main(String args[])  ListInteger> numList = new ArrayList<>(); numList.add(1); Integer [] numArray = numList.stream().toArray( n -> new Integer[n]); > 

Java Versions Tested

The examples in this post were compiled and executed using Java 8. Everything contained in this post is accurate to all versions up to Java 13 (which is the latest version.)

The following video illustrates the difference between ArrayLists and Arrays, advantages and performance comparison of the two.

#java #arraylist #arrays #boost

You May Also Enjoy

If you like this post, please share using the buttons above. It will help CodeAhoy grow and add new content. Thank you!

Comments (1)

Harry Henry Gebel

An array of Integers is not an array of ints.

Источник

Java ArrayList.toArray()

Learn to convert ArrayList to an array using toArray() method. The toArray() method returns an array that contains all elements from the list – in sequence (from first to last element in the list).

ArrayList list = . ; Object[] array = list.toArray(); //1 String[] array = list.toArray(new String[list.size()]); //2

The toArray() is an overloaded method:

public Object[] toArray(); public T[] toArray(T[] a);
  • The first method does not accept any argument and returns the Object[]. We must iterate the array to find the desired element and cast it to the desired type.
  • In second method, the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. After filling all array elements, if there is more space left in array then ‘null’ is populated in all those spare positions.

2. ArrayList toArray() Examples

Java program to convert an ArrayList to Object[] and iterate through array content.

ArrayList list = new ArrayList<>(); list.add("A"); list.add("B"); list.add("C"); list.add("D"); //Convert to object array Object[] array = list.toArray(); //Iterate and convert to desired type for(Object o : array) < String s = (String) o; //This casting is required System.out.println(s); >

Java program to convert an ArrayList to String[].

ArrayList list = new ArrayList<>(2); list.add("A"); list.add("B"); list.add("C"); list.add("D"); String[] array = list.toArray(new String[list.size()]); System.out.println(Arrays.toString(array));

Источник

Читайте также:  Jquery css function undefined
Оцените статью