How to convert an Array to Collection like Set and List in Java? Example Tutorial (original) (raw)
Hello Java programmer, if you are wondering how to convert an Array to Collection like Set or List in Java then you have come to the right place. In the past, I have shared how to convert ArrayList to HashMap in Java and In this example, we will learn how to convert a String array to Collection, Set or List in Java. You can convert an Array to Collection using helper method Arrays.asList() in Java. This is shortcut to convert array to List , Set or any Collection. This knowledge of_converting an array to Collection_ can be really useful to any Java developer, as most legacy code tend to use an array, which means you either need to pass them your input as array or they return the result as an array.
Since newer Java code_prefer Collection over the array_, which they should, because of flexibility offered by Collection classes, we often need to convert Array into different Collection classes like List, Set or simply Collection. Its also best practice advised by Joshua Bloch in the class book Effective Java, a must read for Java programmers.
I have shown a couple of techniques forconverting array to ArrayList, which equally applicable, when it comes to convert Array to List in Java. In this article, we will go a couple of steps further and not only learn converting an array to List but also array to Set and array to Collection in Java.
Well, it's only one method, which you need to know, Arrays.asList(), which accepts an array and return a List, later you can convert this List into any other Collection, by usingcopy constructor provided by Collection classes.
Java Example to Convert Array to Collection, Set and List
As I said, it's a cakewalk, once you know about Arrays.asList() and how to use it, you are done. Later you can use a different conversion constructor provided by Collection class to convert one collection to another like List to Set and so on.
Here are steps to convert an Array to Collection in Java:
Convert Array to List using Arrays.asList() method
Store that as Collection
And, here are steps to convert an Array to Set in Java:
Convert Array to List
Create Set by copying objects form List
And last, steps to convert an Array to List in Java:
- Arrays.asList() returns a List, so no further conversion.
If you follow this blog, then you might remember that we have already seen use of Arrays.asList() method in an earlier article,How to create and initialize List in one line, and we have also discussed there that List returned by Arrays.asList() method is a fixed-length list, which means it doesn't support add() and remove() method.
If you try to add or remove an object from this list, you will get "Exception in thread "main" java.lang.UnsupportedOperationException". By the way, it's worth knowing that this List is not aread only List in Java, as you can still update values by using the set(index) method.
Java Program to Convert Array to List and Set in Java
And, here is the complete Java program to convert a given array into Collection and then any type of Set or List like HashSet or ArrayList in Java. You can use this code in your application as well.
import java.util.Arrays; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
/**
Java program to convert array to Collection, List and Set in Java.
Here we will see example of converting String and Integer array to respective
Collection e.g. Set and List.
@author Javin Paul */ public class ArrayToCollectionTest { private static final Logger logger = LoggerFactory.getLogger(ArrayToCollectionTest .class); public static void main(String args[]) {
// Converting String array to Collection, Set and List in Java String[] operatingSystems = new String[]{"Windows", "Linux", "Android", "iOS", "Solaris"}; logger.info("Elements in array : {}", Arrays.toString(operatingSystems)); // Convert array to Collection in Java Collection collection = Arrays.asList(operatingSystems); logger.info("Objects in collection : {},", collection); // Convert String array to Set in Java Set set = new HashSet(Arrays.asList(operatingSystems)); logger.info("Elements in Set : {},", set); // Convert String array to List in Java List list = Arrays.asList(operatingSystems); logger.info("List created from Array in Java : {}", list); // Converting Integer array to Collection, List and Set in Java Integer[] scores = new Integer[]{101, 201, 301,401}; logger.info("Contents of Integer array : {}", Arrays.toString(scores)); // Creating Collection from Integer array in Java Collection iCollection = Arrays.asList(scores); logger.info("Java Collection created from Integer array: {}", iCollection); // Creating List form Integer array in Java List iList = Arrays.asList(scores); logger.info("List created from integer array : {}", iList); // Example of Converting Integer array to HashSet in Java Set iSet = new HashSet(iList); logger.info("Integer array to Set in Java {}", iSet);
}
}
Output [main] - Elements in array : [Windows, Linux, Android, iOS, Solaris] [main] - Elements in array : [Windows, Linux, Android, iOS, Solaris] [main] - Objects in collection : [Windows, Linux, Android, iOS, Solaris], [main] - Elements in Set : [Linux, Windows, Android, Solaris, iOS], [main] - List created from Array in Java : [Windows, Linux, Android, iOS, Solaris] [main] - Contents of Integer array : [101, 201, 301, 401] [main] - Java Collection created from Integer array: [101, 201, 301, 401] [main] - List created from integer array : [101, 201, 301, 401] [main] - Integer array to Set in Java [101, 201, 401, 301]
Dependency
Here, I have used SL4J over Log4j for logging, which means you either need to convert log statement to System.out.println() statements, or you need to include following dependency in your Maven project's pom.xml or log4j-1.2.16.jar, slf4j-api-1.6.1.jar and slf4j-log4j12-1.6.1.jar in yourJava program's classpath.
org.slf4j slf4j-log4j12 1.6.1That's all on How to convert an array to Collection in Java. We have seen examples of converting both String and Integer array to Collection, List, and Set in Java. You can same technique and same method Arrays.asList() to convert any Array to Collection in Java.
Related Java tutorials to learn Collection Framework in Java
- When to use ArrayList and LinkedList in Java
- 5 difference between HashMap and Hashtable in Java
- How to sort HashMap in Java
- Difference between List, Set, and Map in Java
- 10 ways to use HashMap in Java
- How to loop over ArrayList in Java
- 10 Example of ConcurrentHashMap in Java
- How to iterate over an HashMap in Java?
- 21 HashMap Interview Questions with Answers
- 5 Best Online Courses to learn Collections in Java
- 10 ConcurrentHashMap Interview Questions with Answers
Remember, when you create a List from the array, you will get elements in the same order, as they are currently in the array, but when you convert them to Set, you lose any ordering guarantee.