Converting array to list and list to array in Java

I don’t understand why I can’t keep in mind these simple methods.
Last months I used them very often,these methods are very useful.Today I had simple task and I searched in the internet these methods because I couldn’t recollect them.
I am going to show simple example where I will use these methods. After this post I will know where I can find them if they will need. Okay.

How to convert array to the list?
Need to use asList static method in Arrays class.

How to convert list to the array?
Need to use toArray method from List

Example:

import java.util.Arrays;import java.util.List;public class Main{ public static void main(String[] args){ String[] arrayItems = new String[3]; arrayItems[0] = "Oleg"; arrayItems[1] = "Mazurashu"; arrayItems[2] = "FaYnaSoft Labs"; List<String>list = Arrays.asList(arrayItems); System.out.println("list item 5:" + list.get(2)); String[] newArray = new String[list.size()]; list.toArray(newArray); System.out.println("array item 5:" + newArray[2]); }}

It is very simple example. Here I create array with some String objects.
After I convert array to the list:

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

And then I convert list to the array:

String[] newArray = new String[list.size()];list.toArray(newArray);

These operations are very simple and useful.

I hope after this post I will not forget these very useful methods :)

Share

No related posts.

2 comments to Converting array to list and list to array in Java

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.