How To Convert Array To List In Java

In Java, arrays and lists are two different data structures that are commonly used to store and manipulate collections of elements. While arrays are fixed in size and have a specific type, lists can grow and shrink dynamically and can contain elements of different types.

There are situations where you might want to convert an array into a list, such as when you need to perform certain operations on the elements of the collection that are easier to do with a list. To convert an array into a list in Java, you can use the Arrays.asList(), Collections.addAll(), Stream.of() etc.

After converting an array into a list, you can use the various methods available in the List interface to manipulate the list, such as adding or removing elements, iterating over the elements, and sorting the list.

Why There Is A Need For Converting Array To List In Java.

  1. Arrays have a fixed size, whereas lists can grow and shrink dynamically. If you need to add or remove elements from a collection, a list is a more flexible option.
  2. The List interface provides several useful methods for manipulating collections, such as sorting, searching, and iterating. By converting an array to a list, you can take advantage of these methods.
  3. Java APIs and libraries require a List object as input, rather than an array. Converting an array to a list allows you to use these APIs and libraries with your data.
  4. Lists can contain elements of different types, whereas arrays can only contain elements of the same type. If you have an array of objects of different types, converting it to a list allows you to store them together in a single collection.
  5. Working with lists can be more convenient and expressive than working with arrays.

Four Methods For Converting Array To List In Java:.

  1. Arrays.asList()
  2. Collections.addAll()
  3. Stream.of()
  4. Arrays.stream().

 Approach In Details:

Approach 1 – By Using `Arrays.asList()`

This method takes an array as an argument and returns a fixed-size list that is backed by the original array. Any changes made to the list will be reflected in the original array. The `Arrays.asList()` method returns a fixed-size list that is backed by the original array. Any changes made to the list will be reflected in the original array, and vice versa. This can be useful when you need to manipulate an array using the methods provided by the List interface.

Sample Code:

import java.util.Arrays;
import java.util.List;
 
public class ArrayToListExample {
	public static void main(String[] args) {
    	// Create an array of integers
    	Integer[] array = {1, 2, 3, 4, 5};
 
    	// Convert the array to a list
    	List<Integer> list = Arrays.asList(array);
 
    	// Print the original array and the converted list
    	System.out.println("Original array: " + Arrays.toString(array));
    	System.out.println("Converted list: " + list);
	}
}

Output:

Original array: [1, 2, 3, 4, 5]
Converted list: [1, 2, 3, 4, 5]

Explanation:

  1. In this example, first create an array of integers called array.
  2. Then use the `Arrays.asList()` method to convert the array to a list called list.
  3. Then print both the original array and the converted list using the `Arrays.toString()` method and the `toString()` method of the List interface.
  4. The output shows that the original array and the converted list contain the same elements in the same order.

 Approach 2 – By Using ` Collections.addAll()`

This method takes a collection and one or more elements and adds them to the collection. You can use it to convert an array to a list by creating an empty list and adding the elements of the array to it. The `Collections.addAll()`  method takes a collection as the first argument, followed by one or more elements. It adds the elements to the collection, in the order in which they appear in the argument list.

Sample Code:

import java.util.LinkedList;
import java.util.Collections;
import java.util.List;
 
public class Example {
	public static void main(String[] args) {
// Create an array of strings
    	String[] array = {"apple", "banana", "orange", "kiwi"};
 
 // Convert the array to a list
    	List<String> list = new LinkedList<>();
    	Collections.addAll(list, array);
// Print the original array and the converted list 
    	System.out.println("List: " + list);
	}
}

Output:

List: [apple, banana, orange, kiwi]

Explanation:

  1. Create an array of strings named array.
  2. Then create an empty LinkedList named list.
  3. Use the `Collections.addAll()` method to add all elements from the array to the list.
  4. Finally, print the list to the console using `System.out.println()`.
  5. The output shows that the list contains all elements from the original array.
  6. Note: a LinkedList instead of an `ArrayList` in this example, but the `Collections.addAll()` method works with any implementation of the List interface.

Approach 3 – By Using ` Stream.of()`

This method takes a varargs argument and returns a stream of the elements. You can use it to convert an array to a list by creating a stream of the array elements and collecting them into a list. The Stream.of() method can be used to create a stream of any type of array, including primitive types. The boxed() method is used to convert primitive values to their corresponding wrapper objects, which can then be added to the list.

Sample Code:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
 
public class Example {
	public static void main(String[] args) {
// Create an array
    	String[] array = {"apple", "banana", "cherry", "date", "elderberry"};
 // Convert the array to a list
    	List<String> list = Stream.of(array)
                         	     .filter(s -> s.startsWith("a") || s.startsWith("c"))
                                  .map(String::toUpperCase)
                              	.sorted()
                                  .collect(Collectors.toList());
 	// Print the original array and the converted list  
    	System.out.println("List: " + list);
	}
}

Output:

List: [APPLE, CHERRY]

Explanation:

  1. Create an array of strings named array.
  2. Then use the `Stream.of()` method to create a Stream of elements from the array.
  3. Chain together several stream operations to filter, transform, and sort the elements. First, use the `filter()` method to only keep elements that start with “a” or “c”.
  4. Next, use the `map()` method to convert each string to uppercase.
  5. Then, use the `sorted()` method to sort the elements in alphabetical order.
  6. Finally, use the `collect()` method with `Collectors.toList()` to collect the elements into a List and store it in the list variable.
  7. The list contains only the strings “APPLE” and “CHERRY”, which are the elements that satisfy the filtering criteria and are sorted in alphabetical order.
  8. Print the list to the console using `System.out.println()`.

Approach 4 – By Using ` Arrays.stream()`

This method takes an array as an argument and returns a stream of the elements. You can use it to convert an array to a list by creating a stream of the array elements and collecting them into a list.

Sample Code:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
 
public class ArrayToListExample {
	public static void main(String[] args) {
    	// Create an array of custom objects
    	Person[] people = {
            	new Person("Alice", 25),
            	new Person("Bob", 30),
            	new Person("Charlie", 35)
    	};
 
    	// Convert the array to a list
    	List<Person> list = Arrays.stream(people).collect(Collectors.toList());
 
    	// Print the original array and the converted list
    	System.out.println("Original array: " + Arrays.toString(people));
    	System.out.println("Converted list: " + list);
	}
}
 
class Person {
	private String name;
	private int age;
 
	public Person(String name, int age) {
    	this.name = name;
    	this.age = age;
	}
 
	@Override
	public String toString() {
    	return "Person{" +
            	"name='" + name + '\'' +
            	", age=" + age +
            	'}';
	}
}

Output:

Original array: [Person{name='Alice', age=25}, Person{name='Bob', age=30}, Person{name='Charlie', age=35}]
Converted list: [Person{name='Alice', age=25}, Person{name='Bob', age=30}, Person{name='Charlie', age=35}]

Explanation:

  1. Create an array of custom Person objects. Then use the `Arrays.stream()` method to create a stream of the elements in the array.
  2. Collect the elements of the stream into a list using the `Collectors.toList()` method. Since the Person class is not a primitive type no need to use the `boxed()` method.
  3. The `Arrays.stream()` method automatically creates a stream of Person objects, which can then collect into a list.

Best Approach For Converting Array To List In Java:

There is no one “best” approach for converting an array to a list in Java, as the most appropriate method to use will depend on the specific requirements of your code. The choice of method will depend on factors such as the type of array, the size of the array, and the performance requirements of your code.

However, the `Arrays.asList()` method is a commonly used approach for converting an array to a list in Java.

  1. It is simple and efficient, and works well for small to medium-sized arrays.
  2. It also creates a List that is backed by the original array, meaning that changes made to the List will be reflected in the original array.

Sample problem for converting Array To List In Java.

Sample Problem 1

Problem:

Suppose you are building a shopping application where you need to display a list of products with their names, prices, and available stock. You have an array of Product objects, each containing information about a single product. To display this information in a user-friendly way, you want to convert the array into a list of strings, where each string contains the product name, price, and available stock.

Solution:

You can use the Arrays.asList() method in Java to convert the array to a list, and then process each element of the list to create the desired output.

Code

import java.util.Arrays;
import java.util.List;

public class Product {
//Created a Product class
    private String name;
    private double price;
    private int stock;

    public Product(String name, double price, int stock) {
//Define the product details
        this.name = name;
        this.price = price;
        this.stock = stock;
    }

    public String getName() {
        return name;
    }

    public double getPrice() {
        return price;
    }

    public int getStock() {
        return stock;
    }

    public String toString() {
        return name + ": $" + price + " (Stock: " + stock + ")";
    }

    public static void main(String[] args) {
//Create an Array 
        Product[] products = {
                new Product("Apple", 1.50, 10),
                new Product("Banana", 0.99, 20),
                new Product("Orange", 2.00, 5),
                new Product("Grape", 3.99, 2),
                new Product("Pineapple", 5.50, 7)
        };
// Convert the array to a list
        List<Product> productList = Arrays.asList(products);

        for (Product product : productList) {
            System.out.println(product.toString());
        }
    }
}

Output:

Apple: $1.5 (Stock: 10)
Banana: $0.99 (Stock: 20)
Orange: $2.0 (Stock: 5)
Grape: $3.99 (Stock: 2)
Pineapple: $5.5 (Stock: 7)

Explanation:

  1. Created a Product class that represents a single product with a name, price, and available stock.
  2. Then created an array of Product objects, each containing information about a single product. Display this information by using the `Arrays.asList()` method to convert the array to a list.
  3. Iterate over each element of the list using a for-each loop and call the `toString()` method of each Product object to create the desired output.
  4. The`toString()` method returns a string that contains the product name, price, and available stock in a user-friendly format.
  5. Finally, print each string by using the System.out.println() method.

Sample Problem 2

Problem:

Suppose you have a list of employee objects, and you want to add some new employees to the list. You have the information for the new employees in an array, and you want to convert that array to a list and add it to the existing employee list using the Collections.addAll() method.

Solution:

We can use the `Collections.addAll()` method to add the elements of both arrays to a new `ArrayList`, and then use the `Collections.sort()` method to sort the element defined in the Employee class.

Code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Employee {
    private String name;
    private int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public String toString() {
        return name + " (" + age + ")";
    }

    public static void main(String[] args) {
        List<Employee> employees = new ArrayList<>();
        employees.add(new Employee("Alice", 30));
        employees.add(new Employee("Bob", 25));
        employees.add(new Employee("Charlie", 40));

        Employee[] newEmployees = {
            new Employee("Dave", 22),
            new Employee("Eve", 35)
        };

        Collections.addAll(employees, newEmployees);

        for (Employee employee : employees) {
            System.out.println(employee);
        }
    }
}

Output:

Alice (30)
Bob (25)
Charlie (40)
Dave (22)
Eve (35)

Explanation:

  1. A list of employee objects stored in an ArrayList called employees.
  2. Then create an array of new Employee objects called newEmployees, which we can add to the employees list.
  3. To add the new employees to the list,  use the `Collections.addAll()            ` method.
  4. This method takes two arguments: a collection to which the elements will be added, and an array of elements to be added to the collection.
  5. Pass the employees list as the first argument and the newEmployees array as the second argument.
  6.  The `Collections.addAll()` method adds each element from the newEmployees array to the end of the employees list.
  7. Finally, use loop through the employees list using a for-each loop and print out the name and age of each employee using the toString() method.

Sample Problem 3

Problem:

You have an array of strings containing names of books in a library. You need to convert this array to a list of Book objects. Each Book object should have a title, author, and ISBN number. Use the Stream.of() method to convert the array to a list of Book objects.

Solution:

Create a Book class with a constructor that takes in the title, author, and ISBN number as arguments. Then  use the `Stream.of()` method to convert the array to a stream of strings and use the `map()` method to convert each string to a Book object. Finally, use the `collect()` method to collect the stream into a list.

Code:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        String[] bookTitles = {"The Great Gatsby", "To Kill a Mockingbird", "Pride and Prejudice"};
        List<Book> books = Stream.of(bookTitles)
                .map(title -> new Book(title, "Unknown", "Unknown"))
                .collect(Collectors.toList());
        System.out.println(books);
    }
}

class Book {
    private String title;
    private String author;
    private String isbn;

    public Book(String title, String author, String isbn) {
        this.title = title;
        this.author = author;
        this.isbn = isbn;
    }

    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + '\'' +
                ", author='" + author + '\'' +
                ", isbn='" + isbn + '\'' +
                '}';
    }
}

Output:

[Book{title='The Great Gatsby', author='Unknown', isbn='Unknown'}, Book{title='To Kill a Mockingbird', author='Unknown', isbn='Unknown'}, Book{title='Pride and Prejudice', author='Unknown', isbn='Unknown'}]

Explanation:

  1. Start by declaring an array of book titles called bookTitles.
  2. Then use the `Stream.of()` method to convert this array to a stream of strings.
  3. Then use the `map()` method to convert each string to a Book object.
  4. In the `map()` method, create a new Book object for each string using the new keyword and passing in the title, “Unknown” for the author, and “Unknown” for the ISBN number.
  5. Finally, use the `collect()` method to collect the stream into a list of Book objects called books. Print out the books list using the `System.out.println()` method.

Sample Problem 4

Problem:

You have an array of integers representing the sales made by your sales team in a month. You need to find the total sales and average sales for the month and store them in a list using Arrays.stream() method.

Solution:

Use the `Arrays.stream()` method to convert the integer array to a stream and then use stream methods like `sum()` and `average()` to find the total and average sales. Then create a new list and add the total and average sales to it.

Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        int[] sales = {1000, 2000, 3000, 4000, 5000};

        // Find total and average sales
        int totalSales = Arrays.stream(sales).sum();
        double averageSales = Arrays.stream(sales).average().orElse(Double.NaN);

        // Create list and add total and average sales
        List<Object> salesList = new ArrayList<>();
        salesList.add(totalSales);
        salesList.add(averageSales);

        // Print the sales list
        System.out.println("Sales List: " + salesList);
    }
}

Output:

Sales List: [15000, 3000.0]

Conclusion:

In conclusion, there are multiple ways to convert an array to a list in Java, each with its own advantages and disadvantages. The `Arrays.asList()` method is simple to use and has good performance, but the resulting list is fixed-size.

The `Collections.addAll()` method is flexible and can be used with any collection, but it requires an extra step to create the collection and can have lower performance for larger arrays.

The `Stream.of()` method is flexible and can be used with any type of array. The `Arrays.stream()` method is flexible and can be used with primitive arrays, but it requires additional operations to convert the stream to a list.