In this post, we will see how to convert Java Collection to List.
There are many ways to do it, we will see two ways here.
Using ArrayList constructor
1 2 3 |
ArrayList(Collection<? extends E> c) |
Above ArrayList‘s constructor creates a list having the elements of the specified collection, in the order they are returned by the collection’s iterator.
Using Java 8 Stream
You can use Java 8‘s stream as well to convert any collection to the List.
1 2 3 |
List<Integer> intValuesJava8 = values.stream().collect(Collectors.toList()); |
Complete program for converting Java Collection to List.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
package org.arpit.java2blog; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class ConvertCollectionToListMain { public static void main(String[] args) { // HashSet Collection<String> s1 = new HashSet<>(); s1.add("John"); s1.add("Martin"); s1.add("Mary"); System.out.println("Set Elements:"); System.out.println(s1); // Converting Collection to list List<String> list=new ArrayList<String>(s1); System.out.println("List elements: "); System.out.println(list); // HashMap Map<String,Integer> m1 = new HashMap<>(); m1.put("John", 18); m1.put("Martin", 23); m1.put("Mary",34); m1.put("Tom", 32); System.out.println("==================="); Collection<Integer> values = m1.values(); // Converting Collection to list List<Integer> intValues = new ArrayList<>(values); System.out.println("Values of Map are: "); System.out.println(intValues); System.out.println("==================="); System.out.println("Using Java 8"); // Converting Collection to list using java 8 List<String> listJava8= s1.stream().collect(Collectors.toList()); System.out.println("List elements: "); System.out.println(listJava8); // Converting Collection to list using java 8 List<Integer> intValuesJava8 = values.stream().collect(Collectors.toList()); System.out.println("Values of Map are: "); System.out.println(intValuesJava8); } } |
When you run above program, you will get below output
[John, Martin, Mary]
List elements:
[John, Martin, Mary]
===================
Values of Map are:
[32, 18, 23, 34]
===================
Using Java 8
List elements:
[John, Martin, Mary]
Values of Map are:
[32, 18, 23, 34]
That’s all about Java collection to List.