Java Program to Convert Array into Collection

JavaCampus InterviewServer Side ProgrammingProgramming

In this article, we will understand how to convert array into collection. The Collection is a framework that provides architecture to store and manipulate the group of objects. Java Collections can achieve all the operations that you perform on a data such as searching, sorting, insertion, manipulation, and deletion.

Below is a demonstration of the same −

Suppose our input is

Input array: [Java, Python, Scala, Shell]

The desired output would be

After elements after converting the array to a list are: [Java, Python, Scala, Shell]

Algorithm

Step 1 - START
Step 2 - Declare a string array namely input_array and a list namely result_list.
Step 3 - Define the values.
Step 4 - Convert the string array to a collection by assigning Arrays.asList(input_array) to the result list.
Step 5 - Display the result.
Step 6 - Stop

Example 1

Here, we bind all the operations together under the ‘main’ function.

import java.util.*;
public class Demo {
   public static void main(String args[]){
      String input_array[] = { "Java", "Python", "Scala", "Shell" };
      System.out.println("The array is defined as: " + Arrays.toString(input_array));
      List result_list = Arrays.asList(input_array);
      System.out.println("
After elements after converting the array to a list are: " + result_list);
   }
}

Output

The array is defined as: [Java, Python, Scala, Shell]

After elements after converting the array to a list are: [Java, Python, Scala, Shell]

Example 2

Here, we encapsulate the operations into functions exhibiting object oriented programming.

import java.util.*;
public class Demo {
   static void convert_to_list(String input_array[]){
      List result_list = Arrays.asList(input_array);
      System.out.println("
After elements after converting the array to a list are: " + result_list);
   }
   public static void main(String args[]){
      String input_array[] = { "Java", "Python", "Scala", "Shell" };
      System.out.println("The array is defined as: " + Arrays.toString(input_array));
      convert_to_list(input_array);
   }
}

Output

The array is defined as: [Java, Python, Scala, Shell]

After elements after converting the array to a list are: [Java, Python, Scala, Shell]
raja
Updated on 30-Mar-2022 06:47:00

Advertisements