ArrayList in Java| Example, Methods (Add, Remove Iterate, Sort)

ArrayList in Java| Example, Methods (Add, Remove Iterate, Sort)

In the previous tutorial, we have seen what Collections in Java are and learned about HashMap in Java. Now let’s dive into Java ArrayLists.

What are ArrayLists in Java?

Collections in Java allow us to insert and delete elements with the help of the List interface. The List interface is an ordered collection of objects which allows the storage of duplicate values. 

ArrayList in Java is a class in Java that implements the features of List interface and has a base of the structure Array.

Properties of ArrayList:

  • An ArrayList is a re-sizeable model of the array that implements all the List interface operations.
  • ArrayList in Java allows us to insert null or duplicate values into the List.
  • Being a List it also maintains the order of insertion, i.e., any element inserted before will be placed in an index value lower than that of the element which is inserted after it.
  • To rephrase it, the first element will be inserted in the first position, the second element in the second position, so on and so forth.  

After knowing the very bit of an ArrayList, let us check out how to create an ArrayList.

How to create an ArrayList in Java?

Proceeding further, this is how we can create an ArrayList in Java,

ArrayList<Type> arrayListName = new ArrayList<>();  

Where, Type equals to any form of data type or Object.

For example:

Creating an Integer ArrayList.

ArrayList<Ineger> intergerList = new ArrayList<>();

Creating an ArrayList of students

ArrayList<Student> studentList = new ArrayList<>();

An ArrayList can also be created with the help of List, for example

List<Ineger> integerList = new ArrayList<>();

Now, as we know how to create an ArrayList, let us look into a basic example to create an ArrayList and then print it.

Iterating an ArrayList

In the below example, we will be creating a list of brands called brandList that will store values in the form of Java String. Sticking to the basics, to create an ArrayList we need to first import java.util.ArrayList or its superclass.

import java.util.ArrayList;
public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> brandList = new ArrayList<>();
	
    //Adding elements to the ArrayList.
    brandList.add("Nike");
    brandList.add("Coca-Cola");
    brandList.add("Titan");

    //Printing the elements in the ArrayList.
    System.out.println("Values in the list are:= "+brandList);

    //Iterating the ArrayList using for- loop.
    System.out.println("====Using for loop====");
    for(int i = 0; i < brandList.size(); i++) {
      System.out.println(brandList.get(i));
    }
    //Iterating the ArrayList using for-each loop.
    System.out.println("====Using for-each loop====");
    for(String brands : brandList) {
      System.out.println(brands);
    }
    //Iterating the ArrayList using forEach method of Java 8.
    System.out.println("====Using forEach method of Java 8====");
    brandList.forEach((brand) -> System.out.println(brand));
 }
}

Output:

The output of the above program is as follows:

Values in the list are:= [Nike, Coca-Cola, Titan]
====Using for loop====
Nike
Coca-Cola
Titan
====Using for-each loop====
Nike
Coca-Cola
Titan
====Using forEach method of Java 8====
Nike
Coca-Cola
Titan

Methods of Java ArrayList

In the above basic example, we have observed the use of add()  and get() methods. ArrayList in Java has a number of varied methods that allow different operations to be performed. Let us now take a small ride to methods supported by ArrayLists and know a bit about them.

ArrayList Methods Description
1 boolean add(Object e) adds specified element to the end of the list
2 void add(int index, Object e) adds a specified element in specified position of the list
3 boolean addAll(Collection e) adds specified Collection to the end of the list
4 void addAll(int index, Collection e) adds specified Collection to the specified position of the list
5 void clear() removes all the elements present in the ArrayList
6 boolean contains(Object e) checks for the existence of the specified element in the list and true if it exists, else returns false
7 Object get(int index) fetches the element present in the specified position from the list
8 boolean remove(Object e) removes the specified element from the list
9 Object remove(int index) removes the element from the specified position of the list
10 Object set(int index, Object e) replaces the element at the specified index position with the specified element
11 boolean isEmpty() checks if the particular list is empty and return true else return false
12 int indexOf(Object e) returns the index of the first occurrence of the specified element, else returns -1 if the element is not found in the list

Operations on ArrayList

Varied operations that can be performed on an ArrayList.

Adding elements in ArrayList

One can add elements in ArrayList with the help of

  • add(Object e)
    – allows insertion of elements in a specified list
  • add(int index, Object e)
    – allows insertion of elements at the specified position in the list
  • addAll(Collection<? extends E> e)
    – allows insertion of Collection into the list

Below is the example of adding elements into an ArrayList in Java.

import java.util.ArrayList;

public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> fruitList = new ArrayList<>();
	
    //Adding elements to the ArrayList.
    fruitList.add("Apple");
    fruitList.add("Banana");
	
    //Adding elements at a specific index
    fruitList.add(2, "Mango");
    fruitList.add(3, "Guava");

    //Printing the elements in the ArrayList.
    System.out.println("Values in the list are:= "+fruitList);

    //Creating a sample list.
    ArrayList<String> sampleList = new ArrayList<>();

    //Adding elements to the new list.
    sampleList.add("Grapes");
    sampleList.addAll(fruitList);

    //Printing the elements in the ArrayList.
    System.out.println("Values in the list are:= "+sampleList);
  }
}

Output:

The output of the above code is as follows:

Values in the list are:= [Apple, Banana, Mango, Guava]
Values in the list are:= [Grapes, Apple, Banana, Mango, Guava]

Accessing elements in ArrayList

One can access the elements present in the ArrayList with the help of get() or iterator().

  • get(int index)
    – allows to fetch the element at the specified position.
  • iterator()
    – allows to access all the elements present in the ArrayList sequentially.

Below is the example that will help us know the method of accessing elements from an ArrayList.

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> fruitList = new ArrayList<>();

    //Adding elements to the ArrayList.
    fruitList.add("Apple");
    fruitList.add("Banana");
    fruitList.add("Mango");
    fruitList.add("Grapes");

    //Printing the elements in the ArrayList.
    System.out.println("Values in the list are:= "+fruitList);

    //Fetching the element at the index position '1'.
    System.out.println("Element at position '1' is := " +fruitList.get(1));
	
    //Accessing all the elements in the ArrayList using Iterator.
    Iterator<String> itr = fruitList.iterator();
    System.out.println("Accessing the values in list using Iterator := ");

    //hasNext() retruns true if there is a next element in the list, else false.
    while(itr.hasNext()) {	
      //next() is used to return the next element in the ArrayList.	
      System.out.println(itr.next());		
    }
  }
} 

Output:

The output of the above code snippet would be:

Values in the list are:= [Apple, Banana, Mango, Grapes]
Element at position '1' is := Banana
Accessing the values in list using Iterator :=
Apple
Banana
Mango
Grapes

Removing elements from ArrayList

One can remove elements from an ArrayList with the help of remove(), removeAll() and clear().

  • remove()
    – This method comes with two variants. One allows the user to remove the specified element and the other allows the user to remove an element from a specified position.
  • removeAll()
    – allows the deletion of all the elements from the ArrayList
  • clear()
    – It is similar to removeAll(). clear() also allows the removal of all elements from the list.

Below is the example depicting the removal of elements from an ArrayList

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> fruitList = new ArrayList<>();

    //Adding elements to the ArrayList.
    fruitList.add("Apple");
    fruitList.add("Banana");
    fruitList.add("Mango");
    fruitList.add("Grapes");

    //Printing the elements in the fruits ArrayList.
    System.out.println("Values in the fruitList are:= "+fruitList);

    //Creating a new list called sampleList.
    ArrayList<String> sampleList = new ArrayList<>();
    sampleList.add("Guava");
    sampleList.addAll(fruitList);

    //Printing the elements in the sample ArrayList.
    System.out.println("Values in the sampleList are:= "+sampleList);

    //Removing elements from the sampleList.
    System.out.println("Removing element from index position '1' from the list:= "+sampleList.remove(1));

    //Printing the list after removing element at position ‘1’ of the list.
    System.out.println("Values in the sampleList after removing element from index position '1' are:= "+sampleList);
    System.out.println("Removing element 'Mango' from the list:= "+sampleList.remove("Mango"));

    //Printing the list after removing ‘Mango’ from the list.
    System.out.println("Values in the sampleList after removing 'Mango' are:= "+sampleList);

    //Removing elements from sampleList using rmoveAll().
    sampleList.removeAll(sampleList);

    //Printing the list after removing elements from the list.
    System.out.println("Values in the sampleList are:= "+sampleList);

    //Removing elements from the furitList using clear().
    fruitList.clear();

    //Printing the list after removing elements from the list.
    System.out.println("Values in the fruitList are:= "+fruitList);
  }
}

The expected output of the above program is:

Values in the fruitList are:= [Apple, Banana, Mango, Grapes]
Values in the sampleList are:= [Guava, Apple, Banana, Mango, Grapes]
Removing element from index position '1' from the list:= Apple
Values in the sampleList after removing element from index position '1' are:= [Guava, Banana, Mango, Grapes]
Removing element 'Mango' from the list:= true
Values in the sampleList after removing 'Mango' are:= [Guava, Banana, Grapes]
Values in the sampleList are:= []
Values in the fruitList are:= []

Changing the value of an element in ArrayList

One can change the existing value in the ArrayList with the help of the set() method.

  • set(int index, Object e)
    – replaces the element at the specified index position with the specified element

With the help of the below example, let us try our hands-on replacing an element in the ArrayList.

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> fruitList = new ArrayList<>();

    //Adding elements to the ArrayList.
    fruitList.add("Apple");
    fruitList.add("Banana");
    fruitList.add("Mango");
    fruitList.add("Grapes");

    //Printing the elements in the fruits ArrayList.
    System.out.println("Values in the fruitList are:=  "+fruitList);

    //Replacing "Banana" with "Orange"
    fruitList.set(1,"Orange");

    //Replacing "Grapes" with "Watermelon".
    fruitList.set(3, "Watermelon");

    //Printing the list after replacing the element.
    System.out.println("Values in the fruitList are:=  "+fruitList);
  }
}

Output:

The expected output of the above program is:

Values in the fruitList are:= [Apple, Banana, Mango, Grapes]
Values in the fruitList are:= [Apple, Orange, Mango, Watermelon]

Sorting elements in ArrayList

One can sort the elements in the ArrayList with the help of sort() method which the Collections class provides. To access the sort() method, we must import java.util.Collections package.

Let us look into the below code snippet which will help us sort elements of the ArrayList either alphabetically or numerically in the order of ascending.

import java.util.ArrayList;
import java.util.Collections;

public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> fruitList = new ArrayList<>();

    //Adding elements to the ArrayList.
    fruitList.add("Mango");
    fruitList.add("Watermelon");
    fruitList.add("Guava");
    fruitList.add("Grapes");
    fruitList.add("Banana");
    fruitList.add("Apple");
    
    //Printing the elements in the fruits ArrayList.
    System.out.println("Unsorted list is := "+fruitList);

    //Sorting the elements in the ArrayList.
    Collections.sort(fruitList);
    
    //Printing the sorted list.
    System.out.println("Sorted list is := "+fruitList);
  }
}

Output:

The expected output of the above program looks like,

Unsorted list is := [Mango, Watermelon, Guava, Grapes, Banana, Apple]
Sorted list is := [Apple, Banana, Grapes, Guava, Mango, Watermelon]

Other methods of ArrayList

ArrayList also provides us with few more methods and functionalities, for instance,

  • indexOf()
    – searches specific elements in the ArrayList and it then returns the index position of that element
  • size()
    – returns the size of the list
  • isEmpty()
    – checks if the list is empty or has any elements if empty then returns true else false
  • contains()
    – searches for the specific element in the list and returns true if it exists else false
  • size()
    – returns the size of the list

With the help of an example, let us find out how the above listed methods work,

import java.util.ArrayList;

public class ArrayListExample {
  public static void main(String[] args) {
    ArrayList<String> fruitList = new ArrayList<>();

    //Adding elements to the ArrayList.
    fruitList.add("Mango");
    fruitList.add("Watermelon");
    fruitList.add("Guava");
    fruitList.add("Grapes");
    fruitList.add("Banana");
    fruitList.add("Apple");

    //Printing the elements in the fruits ArrayList.
    System.out.println("Elements of the list are := "+fruitList);

    //To check if the list empty or not.
    System.out.println("Is the list empty?  "+fruitList.isEmpty());
	    
    //To find the position of 'Grapes' in the list.
    System.out.println("Position of 'Grapes' in the list is :=  "+fruitList.indexOf("Grapes"));
	    
    //Print the length of ArrayList.
    System.out.println("Size of the ArrayList is :=  "+fruitList.size());
    
    //To check if list contains 'Orange' or not.
    System.out.println("Does the list contain 'Orange' ?" +fruitList.contains("Orange"));
  }
}

Output:

The expected output of the program is–

Elements of the list are := [Mango, Watermelon, Guava, Grapes, Banana, Apple]
Is the list empty? false
Position of 'Grapes' in the list is := 3
Size of the ArrayList is := 6
Does the list contain 'Orange' ? false

And that’s all about ArrayList in Java. To sum up, in this tutorial we learned about what an ArrayList is, the methods it supports and the operations and functionalities an ArrayList can do.

Happy Learning!

Leave a Reply

Your email address will not be published. Required fields are marked *