Sunday, 13 December 2015

How to convert Array to ArrayList in Java

There may be a situation when you want to convert an array to an ArrayList in order to use some of the methods provided by ArrayList, as example contains to check if an element is there in the list.

If you have this need then Java does provide a class for doing the same called Arrays. Arrays class contains various methods for manipulating arrays (such as sorting and searching). This class also contains a static factory that allows arrays to be viewed as lists. The method to convert Array to ArrayList is asList() whose general form is

public static <T> List<T> asList(T... a)

Using Arrays.asList to convert array to ArrayList

In the following Java code I have an array of cities which I am converting into an ArrayList.

public class CovertToArrayList {
    public static void main(String[] args) {
         String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
         //Converting array to List
         List<String> cityList = Arrays.asList(cityArray);
         for(String name : cityList){
            System.out.println("City : " + name);
         } 
    }
}

There are few points to note about Arrays.asList method

  • This method returns a List that is a view onto the array. You can say it more of a wrapper around an array. That makes it more efficient than any other option as array elemnts are not actually copied to the List.
  • The list returned by this method is a fixed-size list.
  • Since list returned is just a view onto the array, if you change any element in the list that change is reflected in the array too.
  • The ArrayList class used to create the list while using this method Arrays.asList is actually a static class within the Arrays class and many of the methods of the original ArrayList are not supported by this ArrayList. As example add method is not there in this ArrayList so any attempt to add new element to the returned list will throw "UnsupportedOperationException"

Example code

public class CovertToArrayList {

    public static void main(String[] args) {
         String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
         //Converting array to List
         List<String> cityList = Arrays.asList(cityArray);
         // Attempt to add new element in the list
         // This will throw exception
         cityList.add("Pune");
         for(String name : cityList){
            System.out.println("City : " + name);
         }
        
    }

}

Output

Exception in thread "main" java.lang.UnsupportedOperationException
 at java.util.AbstractList.add(Unknown Source)
 at java.util.AbstractList.add(Unknown Source)
 at org.netjs.prog.CovertToArrayList.main(CovertToArrayList.java:16)
  • You can also initialize a list using this method like this
    List<String> cityList = Arrays.asList("Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai");
    
  • As stated above no new element can be added to the List returned by Arrays.asList method. If you have to add new elements to add to the List then there are other options.

    • Wrapping the list returned by Arrays.asList to a new ArrayList.
      public class CovertToArrayList {
          public static void main(String[] args) {
               String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
               //Converting array to List
               ArrayList<String> cityList = new ArrayList<String>(Arrays.asList(cityArray));
              
               cityList.add("Pune");
               for(String name : cityList){
                  System.out.println("City : " + name);
               }     
          }
      }
      

      Output

      City : Delhi
      City : Mumbai
      City : Bangalore
      City : Hyderabad
      City : Chennai
      City : Pune
      

      It can be seen that now new elements can be added to the list.

    • Using Collections.addAll method. Here again a new List is created using the array, by passing both as parameters.
      public class CovertToArrayList {
          public static void main(String[] args) {
               String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
               List<String> cityList= new ArrayList<String>();
               Collections.addAll(cityList, cityArray);
               cityList.add("Pune");
               for(String name : cityList){
                  System.out.println("City : " + name);
               }        
          }
      }
      
    • Using Java 8 Stream

      public class CovertToArrayList {
          public static void main(String[] args) {
               String cityArray[] = {"Delhi", "Mumbai", "Bangalore", "Hyderabad", "Chennai"};
               // Using stream
               List<String> cityList = Stream.of(cityArray).collect(Collectors.toList());
               cityList.add("Pune");
               for(String name : cityList){
                  System.out.println("City : " + name);
               }        
          }
      }
      

      Output

      City : Delhi
      City : Mumbai
      City : Bangalore
      City : Hyderabad
      City : Chennai
      City : Pune
      

    That's all for this topic How to convert Array to ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


    Related Topics

    1. How to convert ArrayList to Array in Java
    2. ArrayList in Java
    3. Difference between Array and ArrayList in Java
    4. Difference between ArrayList and LinkedList in Java
    5. How to join lists in Java
    6. How to loop/iterate an arraylist in Java
    7. Java Collections interview questions

    You may also like -

    2 comments:

    1. One of the few good websites that teaches good java. Keep posting. Thanks!

      ReplyDelete
      Replies
      1. Thanks for the good words and so glad that you like it!

        Delete