How to convert list to array java

How to convert list to array java

Convert list to array in Java [duplicate]

How can I convert a List to an Array in Java?

Check the code below:

11 Answers 11

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way:

Update:

From JetBrains Intellij Idea inspection:

There are two styles to convert a collection to an array: either using a pre-sized array (like c.toArray(new String[c.size()])) or using an empty array (like c.toArray(new String[0]).

In older Java versions using pre-sized array was recommended, as the reflection call which is necessary to create an array of proper size was quite slow. However since late updates of OpenJDK 6 this call was intrinsified, making the performance of the empty array version the same and sometimes even better, compared to the pre-sized version. Also passing pre-sized array is dangerous for a concurrent or synchronized collection as a data race is possible between the size and toArray call which may result in extra nulls at the end of the array, if the collection was concurrently shrunk during the operation.

This inspection allows to follow the uniform style: either using an empty array (which is recommended in modern Java) or using a pre-sized array (which might be faster in older Java versions or non-HotSpot based JVMs).

Converting ArrayList to Array in java

I have an ArrayList with values like «abcd#xyz» and «mnop#qrs». I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:

But it failed saying «Ljava.lang.String;@57ba57ba»

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

12 Answers 12

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

You don’t need to reinvent the wheel, here’s the toArray() method:

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29

Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:

What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you’re printing.

How to Convert List to Array Java

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java Azhwani • Jul 19, 2021 • java • 5 mins read

Table of Contents [ Show ]

In this short article, we are going to explore different ways of converting a list to array in Java.

First, we’ll start by taking a look at the basic approach. Then we’ll dig deeper to see how to achieve the same thing in a more succinct way using Java 8.

Finally, we are going to showcase how to use Guava and Apache Commons libraries to perform the conversion.

Java List to Array

Converting a List into an array can be very handy when we are invoking a third-party method returning a list inside a method that returns an array.

So, let’s see how we can achieve this in Java.

Feel free to check our articles about array conversion in Java:

Using Plain Java

The most basic way to convert a List of objects to an array in Java is to use a loop.

We can iterate over the list and push each element into our array:

Using toArray() Method

toArray() method is defined in the List interface. It returns a simple array containing all of the elements of the given list.

This handy method provides the easiest way to accomplish list array conversion in Java.

Let’s see together how we can use toArray() to convert a collection of String objects into an array:

Using Java 8 Stream.toArray()

Stream API comes with a handy method called Stream.toArray(). We can use this method to return an array containing the elements of a particular list.

This below example illustrates how to convert a list to an array with the help of the Stream.toArray() method:

Using Guava

Now, let’s see how we can use the Guava API to perform the conversion. First thing first, we need to add the Guava dependency in the pom.xml:

Guava comes with a set of utility classes such as Ints, Longs, and Doubles. Each class provides a convenient method called toArray() for converting a list to a primitive array.

The following example showcases how to use Doubles.toArray() to convert a list of Double to an array:

Please bear in mind that the Guava’s toArray() methods will throw a NullPointerException if the specified list or any of its elements is null.

So, to avoid the NPE exception, we need to make sure that the passed list does not hold any null value.

Using Apache Commons Lang

Apache Commons Lang is another great library that provides a host of helper classes. Among these utilities, there is the ArrayUtils class.

ArrayUtils comes with a set of handy methods for performing operations on arrays. For example, it provides the toPrimitives() method to convert an array of wrapper objects to primitives.

Now, let’s see how we can use Apache Commons Lang to convert a list to array:

Handle null Values When Converting List to Array

Handling null values is an important thing to keep in mind, especially when we are converting a List to a primitive array.

As we have mentioned earlier, trying to convert a list that contains a null value may lead to NullPointerException.

So to avoid this scenario, we can use Java 8 to filter on null values:

Conclusion

To sum it up, the native approach is generally enough to convert a list to array in Java.

However, for more advanced ways, we can use Java 8 Stream API or the clean and flexible Guava API.

Liked the Article? Share it on Social media!

Java convert List to Array

In this post, we will see how to convert List to Array in java.

There are many ways to convert List to Array in java

Using toArray() method

Example:

OUTPUT:

Please note that if you do not pass any parameter to toArray() method, it will give us Object array.

Using Java 8’s Stream

We can simply use java 8‘ stream’s toArray() method to convert List to array.

Output:

Using Arrays.copyOf

We can use Arrays.copyOf() method also to convert List to Array. We need to use toArray() method and pass it to Arrays.copyOf() method to convert it to specified type

Output:

Using System.arraycopy

We can use System.arraycopy() method which copies an specified array, starting at the specified position, to the specified position of the target array.

Output:

Manual method

This method use loop and run it until the size of list and one by one get elements from list and add it to Array.

Example:

OUTPUT:

That’s all about converting List to Array in java.

Was this post helpful?

Share this

How to convert String to int in Java

Java Convert Array to List

Author

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

Related Posts

Convert set to String in Python

Table of ContentsWays to convert set to string in PythonUsing the str() functionUsing the repr() functionUsing the join() functionUsing the map() functionConclusionWas this post helpful? Sets are an unordered collection of elements in Python. It does not contain duplicate elements and can be defined using the set() function in Python. Ways to convert set to […]

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

Convert String to Array in Java

Table of ContentsHow to convert String to Array in JavaUsing toArray() method of SetUsing the split() method of String classUsing StringTokenizor classUsing the split() method of StringUtils classUsing split() method of Pattern classConclusionWas this post helpful? When developing applications in Java there are many cases where we will find ourselves converting data from one type […]

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

Convert float to int in Python

Table of ContentsUsing the int() function to convert float to int in PythonUsing the math module functions to convert float to int in PythonUsing ceil()Using trunc()Using floorWas this post helpful? Python provides several in-built functions and modules for datatype conversions. Floating-point numbers can be easily converted to integers using some of these in-built functions. This […]

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

Java BigDecimal to Double

Learn about how to convert BigDecimal to Double in java

Convert a generic list to an array

I have searched for this, but unfortunately, I don’t get the correct answer.

But there is an error thrown:

How to solve this?

UPDATE

I want this method, because sometimes, the type in my code is too long:

I’d hope to call:

FINALLY

It seems impossible to create such a method, thank you all very much!

13 Answers 13

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

You can just call list.toArray(T[] array) and not have to worry about implementing it yourself, but as aioobe said, you can’t create an array of a generic type due to type erasure. If you need that type back, you need to create a typed instance yourself and pass it in.

If you want to produce your method through brute force, and you can guarantee that you’ll only call the method with certain restrictions, you can use reflection:

This approach has problems. As list can store subtypes of T, treating the first element of the list as the representative type will produce a casting exception if your first element is a subtype. This means that T can’t be an interface. Also, if your list is empty, you’ll get an index out of bounds exception.

This should only be used if you only plan to call the method where the first element of the list matches the Generic type of the list. Using the provided toArray method is much more robust, as the argument provided tells what type of array you want returned.

You can’t instantiate a Generic type like you did here:

The problem is the component type of the array that is not String.

Also, it would be better to not provide an empty array such as new IClasspathEntry[0]. I think it is better to gives an array with the correct length (otherwise a new one will be created by List#toArray which is a waste of performance).

Because of type erasure, a solution is to give the component type of the array.

The type C in this implementation is to allow creation of an array with a component type that is a super type of the list element types.

Waiting for reified generics..

As pointed earlier this will work:

And this will also work:

However, in the first case a new array will be generated. You can see how this is implemented in Android:

Worked solution!

Just copy interface and class inside your project. This :

Declare a subclass of BaseDataLayerTransformer

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

I use this simply function. IntelliJ just hates that type cast T[] but it works just fine.

And call looks like this:

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

This gist that I wrote gives a good solution to this problem.

Following siegi’s suggestion on Atreys’ answer, I wrote a constructor which finds the «nearest common ancestor» (NCA) class and uses that class to create the array. If checks for nulls and if the provided Collection is length 0 or all nulls, the default type is Object. It totally ignores Interfaces.

Here are some examples of using it in jshell («unchecked» class warnings removed for brevity):

How to convert list to array java. Смотреть фото How to convert list to array java. Смотреть картинку How to convert list to array java. Картинка про How to convert list to array java. Фото How to convert list to array java

When you have a generic List you will be able to know the class of the object at the runtime. Therefore, the best way to implement it is like this:

Why do you need the Class parameter?

Now, how can you use it?

Simple, just call it like this:

Here is the compiling sample of this: https://ideone.com/wcEPNI

Why does it work?

Note: You won’t be able to get an array of primitives, since primitives can’t be used for type variables.

Источники информации:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *