Computer Science, asked by Lakshita9730, 1 year ago

How to convert an array to a list in Java?

Answers

Answered by vovvie1516
0

this might help you

The following code example demonstrates converting an Array of Strings to a LinkedList of Strings.

Java

import java.util.Arrays;

import java.util.Iterator;

import java.util.LinkedList;

/**

* Java 1.4+ Compatible

* The following example code demonstrates converting an Array of Strings to a LinkedList of Strings

*/

public class Array2LinkedList {

public static void main(String[] args) {

// initialize array with some data

String[] sa = new String[] { "A", "B", "C" };

// convert array to LinkedList

LinkedList ll = new LinkedList(Arrays.asList(sa));

// iterate over each element in LinkedList and show what is in the list.

Iterator iterator = ll.iterator();

while (iterator.hasNext()) {

// Print element to console

System.out.println((String) iterator.next());

}

}

}

import java.util.Arrays;

import java.util.Iterator;

import java.util.LinkedList;

/**

* Java 1.4+ Compatible

* The following example code demonstrates converting an Array of Strings to a LinkedList of Strings

*/

public class Array2LinkedList {

public static void main(String[] args) {

// initialize array with some data

String[] sa = new String[] { "A", "B", "C" };

// convert array to LinkedList

LinkedList ll = new LinkedList(Arrays.asList(sa));

// iterate over each element in LinkedList and show what is in the list.

Iterator iterator = ll.iterator();

while (iterator.hasNext()) {

// Print element to console

System.out.println((String) iterator.next());

}

}

}

Answered by Oreki
2

We can convert an Array to a List by using asList( ) method of Arrays class in java.util package.

For Example:

   Given an Array,

      String[ ] array = {"One", "Two", "Three", "Four", "Five"};

  We can convert it to a List by,

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

Similar questions
Math, 6 months ago