Home  >  Java 9

Convert Array to List in Java

By Arvind Rai, February 05, 2018
This page will walk through how to convert array into list using Java. We can achieve it in many ways such as by using List.of, Stream.collect, Collections.addAll and Arrays.asList methods. List.of and Arrays.asList return immutable List. We can create ArrayList using immutable List to make it mutable. List can be converted back to array using List.toArray() . On this page we will provide examples to convert array into list for String, Integer and custom data types. Now find the complete examples step by step.

1. Java 9: Using List.of

1. List.of is introduced in Java 9. It returns an immutable List. We pass our array to List.of method and it returns an immutable List of same size.
String[] persons = {"Mukesh", "Vishal", "Amar"};
List<String> personList = List.of(persons); 
2. In the above code snippet, the instance personList is immutable. If we add any element in it as below
personList.add("Mohit"); 
It will throw following exception.
Exception in thread "main" java.lang.UnsupportedOperationException 
3. To get a mutable list, we can use ArrayList as following.
List<String> personList = new ArrayList<>(List.of(persons)); 
Now we can add new element in it.
4. We can convert our list back into array using toArray() from the instance of List as following.
Object[] persons = personList.toArray(); 
toArray() returns array containing all the elements of that list in proper sequence i.e. from first to last.

Find the examples to convert array into list using List.of .
ListOf.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
public class ListOf {
  public static void main(String[] args) {
	 System.out.println("---Example-1---");
         String[] persons = {"Mukesh", "Vishal", "Amar"};
	 List<String> personList = List.of(persons);
	 personList.forEach(p-> System.out.print(p + " "));		
     
	 System.out.println("\n---Example-2---");
	 personList = new ArrayList<>(List.of(persons));
	 personList.add("Mohit");
	 personList.forEach(p-> System.out.print(p + " "));
	 
	 System.out.println("\n---Example-3---");
	 Book[] books = Book.getBooks();
	 List<Book> bookList = List.of(books);
	 bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | "));

	 System.out.println("\n---Example-4---");
	 bookList = new ArrayList<>(List.of(books));
	 bookList.add(new Book("Learning Angular", 250));
	 bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 
  }
} 
Output
---Example-1---
Mukesh Vishal Amar 
---Example-2---
Mukesh Vishal Amar Mohit 
---Example-3---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | 
---Example-4---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |  
Book.java
package com.concretepage;
public class Book {
    private String name;
    private int price;
    public Book(String name, int price) {
	  this.name = name;
	  this.price = price;
    }
    public String getName() {
	  return name;
    }
    public int getPrice() {
	  return price;
    }
    @Override
    public boolean equals(final Object obj) {
      if (obj == null) {
         return false;
      }
      final Book book = (Book) obj;
      if (this == book) {
         return true;
      } else {
         return (this.name.equals(book.name) && this.price == book.price);
      }
    }
    @Override
    public int hashCode() {
      int hashno = 7;
      hashno = 13 * hashno + (name == null ? 0 : name.hashCode());
      return hashno;
    }
    public static Book[] getBooks() {
      Book book1 = new Book("Core Java", 200);
      Book book2 = new Book("Learning Freemarker", 150);        	
      Book book3 = new Book("Spring MVC", 300);
      Book[] books = {book1, book2, book3};
      return books;
    }
} 

2. Java 8: Using Stream.collect

Stream is introduced in Java 8 . We can convert array into list using Stream.collect with the help of Collectors.toList and Collectors.toCollection methods. Stream.collect performs a mutable reduction operation on the elements of this stream using a Collector .

2.1 Collectors.toList with Stream.collect

Collectors and Stream are introduced in Java 8. We will convert an array into list using Collectors.toList with Stream.collect methods. Collectors.toList returns a Collector that accumulates the input elements into a new List. Stream.collect performs a mutable reduction operation on the elements of this stream using a Collector . Now find the examples to convert array into list using Collectors.toList with Stream.collect.
CollectorsToList.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsToList {
  public static void main(String[] args) {
      System.out.println("---Example-1---");		
      String[] persons = {"Mukesh", "Vishal", "Amar"};
      List<String> personList = Arrays.stream(persons).collect(Collectors.<String>toList());
      personList.add("Mohit");
      personList.forEach(p-> System.out.print(p + " "));	

      System.out.println("\n---Example-2---");
      Book[] books = Book.getBooks();
      List<Book> bookList = Arrays.stream(books).collect(Collectors.<Book>toList());
      bookList.add(new Book("Learning Angular", 250));
      bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 		
  }
} 
Output
---Example-1---
Mukesh Vishal Amar Mohit 
---Example-2---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |  

2.2 Collectors.toCollection with Stream.collect

We will convert array into list using Collectors.toCollection with Stream.collect methods. Collectors and Stream are introduced in Java 8. Collectors.toCollection returns a Collector that accumulates the input elements into a new Collection, in encounter order. Stream.collect performs a mutable reduction operation on the elements of this stream using a Collector . Now find the example to convert array into list using Collectors.toCollection with Stream.collect.
CollectorsToCollection.java
package com.concretepage;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectorsToCollection {
  public static void main(String[] args) {
     System.out.println("---Example-1---");		
     String[] persons = {"Mukesh", "Vishal", "Amar"};
     List<String> personList = Stream.of(persons).collect(Collectors.toCollection(ArrayList::new));
     personList.add("Mohit");
     personList.forEach(p-> System.out.print(p + " "));	

     System.out.println("\n---Example-2---");
     Book[] books = Book.getBooks();
     List<Book> bookList = Stream.of(books).collect(Collectors.toCollection(ArrayList::new));
     bookList.add(new Book("Learning Angular", 250));
     bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 	
	}
} 
Output
---Example-1---
Mukesh Vishal Amar Mohit 
---Example-2---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |  

2.3 Array of Primitive Numbers into List

To convert array of primitive numbers into list, we need to box these numbers into Integer, Long and Double using IntStream.boxed(), LongStream.boxed() and DoubleStream.boxed() respectively. Arrays.stream returns IntStream if we pass array of int. Arrays.stream returns LongStream if we pass array of long and for double data type, we get DoubleStream . Find the sample example to convert array of int into list of Integer.
CollectorsToListWithInt.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class CollectorsToListWithInt {
  public static void main(String[] args) {
    int[] nums = {12, 14, 16, 20};
    List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.<Integer>toList());
    list.add(30);
    list.forEach(i-> System.out.print(i + " "));
  }
} 
Output
12 14 16 20 30 

3. Java 5: Using Collections.addAll

Collections.addAll adds all of the specified elements to the specified collection. Using Collections.addAll we can convert array into list. Collections.addAll is introduced in Java 5. Find the code to use Collections.addAll to convert array into list.
CollectionsAddAll.java
package com.concretepage;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class CollectionsAddAll {
  public static void main(String[] args) {
    System.out.println("---Example-1---");		
    String[] persons = {"Mukesh", "Vishal", "Amar"};
    List<String> personList = new ArrayList<>();
    Collections.addAll(personList, persons);	
    personList.add("Mohit");
    personList.forEach(p-> System.out.print(p + " "));

    System.out.println("\n---Example-2---");
    List<Book> bookList = new ArrayList<>();
    Book[] books = Book.getBooks();
    Collections.addAll(bookList, books);	
    bookList.add(new Book("Learning Angular", 250));
    bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 	  
  }
} 
Output
---Example-1---
Mukesh Vishal Amar Mohit 
---Example-2---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 |  

4. Java 1.2: Using Arrays.asList

1. Arrays.asList returns a fixed-size list backed by the specified array. It will be an immutable list and we cannot add any element in it. Arrays.asList is introduced in Java 1.2 .
String[] persons = {"Mukesh", "Vishal", "Amar"};
List<String> personList = Arrays.asList(persons); 
2. In the above code snippet, the instance personList is immutable. If we add any element in it as below
personList.add("Mohit"); 
It will throw following exception.
Exception in thread "main" java.lang.UnsupportedOperationException 
3. To get a mutable list, we can use ArrayList as following.
List<String> personList = new ArrayList<>(Arrays.asList(persons)); 
Now we can add new element in it.

Find the examples to convert array into list using Arrays.asList .
ArraysAsList.java
package com.concretepage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ArraysAsList {
   public static void main(String[] args) {
	   System.out.println("---Example-1---");
	   String[] persons = {"Mukesh", "Vishal", "Amar"};
	   List<String> personList = Arrays.asList(persons);
	   personList.forEach(p-> System.out.print(p + " "));

	   System.out.println("\n---Example-2---");
	   personList = new ArrayList<>(Arrays.asList(persons));
	   personList.add("Mohit");
	   personList.forEach(p-> System.out.print(p + " "));
		 
	   System.out.println("\n---Example-3---");
	   Book[] books = Book.getBooks();
	   List<Book> bookList = Arrays.asList(books);
	   bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | "));

	   System.out.println("\n---Example-4---");
	   bookList = new ArrayList<>(Arrays.asList(books));
	   bookList.add(new Book("Learning Angular", 250));
	   bookList.forEach(b-> System.out.print(b.getName()+"-"+ b.getPrice()+" | ")); 
   }
} 
Output
---Example-1---
Mukesh Vishal Amar 
---Example-2---
Mukesh Vishal Amar Mohit 
---Example-3---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | 
---Example-4---
Core Java-200 | Learning Freemarker-150 | Spring MVC-300 | Learning Angular-250 | 

References

List.of
Stream.collect
Collections.addAll
Arrays.asList
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2018 concretepage.com | Privacy Policy | Contact Us