Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a String[] consisting of the .toString() calls of an ArrayList<Object> in one line

So i'm wondering if its possible to populate a String array made from toString() calls of an object ArrayList

So I know this can be done using a loop but is there a one line approach?

Loop approach

ArrayList<Object> objects = new ArrayList<Object>();
//fill object with elements 
//

String[] strings = new String[object.length()];
for(int i = 0;i<10;i++)strings[i]=objects.get(i).toString();
like image 379
user3370533 Avatar asked Aug 11 '16 18:08

user3370533


People also ask

Can you use toString on ArrayList?

Here, we have used the toString() method to convert the arraylist into a string. The method converts the entire arraylist into a single String . Note: The ArrayList class does not have its own toString() method. Rather it overrides the method from the Object class.

What does ArrayList toString method return?

The toString method returns a string representation of an object.

How do you make an array into a string?

Below are the various methods to convert an Array to String in Java: Arrays. toString() method: Arrays. toString() method is used to return a string representation of the contents of the specified array.


1 Answers

Using java-8,

String[] strings = objects.stream().map(Object::toString).toArray(String[]::new);
like image 194
bradimus Avatar answered Oct 05 '22 22:10

bradimus