Monday, May 27, 2013

How to Convert Array to Set and List in Java with Example

In this example we will learn how to convert an String array to Collection, Set or List in Java. This knowledge of converting array to Collection can be really useful to any Java developer, as most of legacy code tend to use array, which means you either need to pass them your input as array or they return result as array. Since newer Java code prefer Collection over array, which they should, because of flexibility offered by Collection classes, we often need to convert Array into different Collection classes e.g. List, Set or simply Collection. I have shown 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 couple of steps further and not only learn converting 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.


Steps to convert Java array to Collection,Set and List in Java

Converting array to collection, set and List in JavaAs I said, it's a cakewalk, once you know about Arrays.asList() and how to use it, you are done. Later you can use different conversion constructor provided by Collection class to convert one collection to other e.g. List to Set and so on.

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

Array to Set in Java
   1) Convert Array to List
   2) Create Set by copying objects form List

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 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 any 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 set(index) method.


Java Program to Convert Array to List and Set in Java

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 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. Remember, when you create List from array, you will get elements in same order, as they are currently in array, but when you convert them to Set, you lose any ordering guarantee.


Related Java tutorials to learn Collection Framework in Java

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

Java67 Headline Animator