Wednesday, June 1, 2022

How to convert an Array to Collection like Set and List in Java? Example Tutorial

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 for converting 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 using copy 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:

   1) Convert Array to List using Arrays.asList() method
   2) Store that as Collection

And, here are steps to convert an Array to Set in Java:
   1) Convert Array to List
   2) Create Set by copying objects form List

And last, steps to convert an Array to List in Java:

   1) 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 a read 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]

    

  


How to convert an Array to Collection like Set and List in Java? Example Tutorial




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 your Java program's classpath.

<dependency> 
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.6.1</version>
</dependency>


That'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

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.

2 comments:

  1. I just surprise that sometime for trivial task like this, I need to do google search. Thanks dude, it certainly helps. I have one question though, when do you prefer to use Array over Collection? It seems Collections are lot better than array, as they are dynamic, they resize automatically, it's easy to add and remove objects from Collection.

    ReplyDelete
    Replies
    1. Many Collections are actually wrapper over array, for example ArrayList is backed up by an array, Hashtable, HashMap uses array as bucket etc. Main reason of array's popularity is the contant time retrieval of element if you know the index. All these data structure either ask for index or first find index then locate element. You can even use array to create your own data structure, e.g. Circular buffer, similar to what Disrupter team has created for LMAX exchange.

      Delete

Feel free to comment, ask questions if you have any doubt.