- Java Programming Examples
- Example - Home
- Example - Environment
- Example - Strings
- Example - Arrays
- Example - Date & Time
- Example - Methods
- Example - Files
- Example - Directories
- Example - Exceptions
- Example - Data Structure
- Example - Collections
- Example - Networking
- Example - Threading
- Example - Applets
- Example - Simple GUI
- Example - JDBC
- Example - Regular Exp
- Example - Apache PDF Box
- Example - Apache POI PPT
- Example - Apache POI Excel
- Example - Apache POI Word
- Example - OpenCV
- Example - Apache Tika
- Example - iText
- Java Tutorial
- Java - Tutorial
- Java Useful Resources
- Java - Quick Guide
- Java - Useful Resources
How to convert an array into a collection in Java
Problem Description
How to convert an array into a collection?
Solution
Following example demonstrates to convert an array into a collection Arrays.asList(name) method of Java Util class.
import java.util.*; import java.io.*; public class ArrayToCollection{ public static void main(String args[]) throws IOException { BufferedReader in = new BufferedReader (new InputStreamReader(System.in)); System.out.println("How many elements you want to add to the array: "); int n = Integer.parseInt(in.readLine()); String[] name = new String[n]; for(int i = 0; i < n; i++) { name[i] = in.readLine(); } List<String> list = Arrays.asList(name); System.out.println(); for(String li: list) { String str = li; System.out.print(str + " "); } } }
Result
The above code sample will produce the following result.
How many elements you want to add to the array: red white green red white green
java_collections.htm
Advertisements