Java List Methods – Sort List, Contains, List Add, List Remove

By Sruthy

By Sruthy

Sruthy, with her 10+ years of experience, is a dynamic professional who seamlessly blends her creative soul with technical prowess. With a Technical Degree in Graphics Design and Communications and a Bachelor’s Degree in Electronics and Communication, she brings a unique combination of artistic flair…

Learn about our editorial policies.
Updated March 10, 2024

This Tutorial Explains Various Java List Methods such as Sort List, List Contains, List Add, List Remove, List Size, AddAll, RemoveAll, Reverse List & More:

We have already discussed the list interface in general in our previous tutorial. List interface has various methods that are used to manipulate the contents of the list. Using these methods you can insert/delete, sort, and search elements in the list.

In this tutorial, we will discuss all the methods that are provided by the list interface.

=> Check Here To See A-Z Of Java Training Tutorials Here.

List Methods

In order to iterate through the list, the list interface makes use of the list iterator. This list iterator extends from the iterator interface. In our next tutorial, we will explore more about the list iterator.

List Methods In Java

The following table shows various functions provided by the list interface in Java.

List methodMethod PrototypeDescription
sizeint size ()Returns the size of the list i.e. number of elements in the List or the length of the list.
clearvoid clear ()Clears the list by removing all the elements in the list
addvoid add (int index, Object element)Adds the given element to the list at the given index
boolean add (Object o)Adds the given element at the end of the list
addAllboolean addAll (Collection c)Appends the entire given collection to the end of the list
boolean addAll (int index, Collection c)Inserts the given collection(all elements) to the list at the specified index
containsboolean contains (Object o)Checks if the specified element is present in the list and returns true if present
containsAllboolean containsAll (Collection c)Checks if the specified collection (all elements) is part of the list. Returns true of yes.
equalsboolean equals (Object o)Compares the specified object for equality with elements of the list
GetObject get (int index)Returns the element in the list specified by index
hashCodeint hashCode ()Returns the hash code value of the List.
indexOf`int indexOf (Object o)Finds the first occurrence of the input element and returns its index
isEmptyboolean isEmpty ()Checks if the list is empty
lastIndexOfint lastIndexOf (Object o)Finds the last occurrence of the input element in the list and returns its index
removeObject remove (int index)Removes the element at the specified index
boolean remove (Object o)Removes the element at its first occurrence in the list
removeAllboolean removeAll (Collection c)Removes all elements contained in the specified collection from the list
retainAllboolean retainAll (Collection c)Opposite of removeAll. Retains the element specified in the input collection in the list.
SetObject set (int index, Object element)Changes the element at the specified index by setting it to the specified value
subListList subList (int fromIndex, int toIndex)Returns sublist of elements between fromIndex(inclusive), and toIndex(exclusive).
sortvoid sort (Comparator c) Sorts the list element as per the specified comparator to give an ordered list
toArrayObject[] toArray ()Returns array representation of the list
Object [] toArray (Object [] a)Returns the array representation whose runtime type is the same as a specified array argument
iteratorIterator iterator ()Returns an Iterator for the list
listIteratorListIterator listIterator ()Returns a ListIterator for the list
ListIterator listIterator (int index)Returns a ListIterator starting at the specified index in the list

Next, we will discuss these functions along with their examples.

size

Prototype: int size()

Parameters: NIL
Return Value: int => Number of elements in the list or in other words the length of the list.
Description: The size() returns the number of elements or the size of the list. It can also be called length in simple terms.

clear

Prototype: void clear()

Parameters: NIL
Return Value: No return value
Description: Clears the list by removing all the elements of the list. Throws “UnSupportedException” if the operation is not supported by the list.

The below example will demonstrate size() and clear() method.

import java.util.*; 
  
public class Main { 
    public static void main(String[] args)  { 
        List<String> strList = new ArrayList<String>();           // Creating a list 
        //add items to list
        strList.add("Java");  
        strList.add("C++");  
        //print the size of list
        System.out.println("Size of list:" + strList.size());  
        //add more items to list
        strList.add("Ruby"); 
        strList.add("Python"); 
        strList.add("C#"); 
        //print the size of list again
        System.out.println("Size of list after adding more elements:" + strList.size());  
        //clear method       
        strList.clear();
       
        System.out.println("List after calling clear() method:" + strList);
      } 
}

Output:

Output of size and clear method

add

Prototype: void add(int index, Object element)

Parameters: index- a position at which the element is to be added.
Element- the element to be added
Return Value: void
Description: Adds the given element to the list at the given index. The subsequent elements are shifted to the right.

Following exceptions are thrown:

IndexOutOfBoundsException: List index is out of range
UnsupportedOperationException: Add operation is not supported by the List.
ClassCastException: The element cannot be added to the list because of the class of specified elements.
IllegalArgumentException: Specified element or some aspect is not correct.

Add

Prototype: boolean add (Object o)

Parameters: o=> Element to be added to the list
Return Value: true=> Element successfully added
False=> Add not successful
Description: This method adds the given element at the end of the list.

This operation can throw the following exceptions.

UnsupportedOperationException: Add operation not supported by this List.
ClassCastException: Specified element cannot be added because of its class
IllegalArgumentException: Specified element or some aspect is not correct.

addAll

Prototype: boolean addAll (Collection c)

Parameters: c=> Collection whose elements are to be added to the list
Return Value: true=> Method execution successful
Description: The addAll method takes all the elements from collection c and appends them to the end of the list by maintaining the order that was set.

This method exhibits unspecified behavior if the collection is altered when the operation is in progress.

The method throws the following exceptions:

UnsupportedOperationException: Add operation not supported by this List.
ClassCastException: Specified element cannot be added because of its class.
IllegalArgumentException: Specified element or some aspect is not correct.

addAll

Prototype: boolean addAll(int index, Collection c)

Parameters: index=> Position at which the collection is to be inserted.
C=> Collection that is to be inserted in the list.
Return Value: true => If collection elements are successfully added to the list.
Description: The addAll method inserts all the elements in the specified collection into the list at the specified index. The subsequent elements are then shifted to the right. As in the case of the previous overload of addAll, the behavior is unspecified if the collection is altered when the operation is in progress.

The exceptions thrown by this method are:

UnsupportedOperationException: Add operation not supported by this List.
ClassCastException: Specified element cannot be added because of its class.
IllegalArgumentException: Specified element or some aspect is not correct.
IndexOutOfBoundsException: Index out of range.

The program below shows the demonstration of add and addAll methods of the list.

import java.util.*; 
  
public class Main { 
    public static void main(String[] args)  { 
        List<String> strList = new ArrayList<String>();           // Creating a list 
        strList.add("Java");  
        strList.add("C++");  
        //print the list
        System.out.println("List after adding two elements:" + strList);  
        List<String> llist = new ArrayList<String>(); 		// Create another list
        llist.add("Ruby"); 
        llist.add("Python"); 
        llist.add("C#"); 
         // addAll method - add llist to strList 
        strList.addAll(llist); 
        System.out.println("List after addAll:"+ strList); 
      } 
}

Output:

Output of add and addAll methods

contains

Prototype: boolean contains(Object o)

Parameters: o=> Element to be searched in the list.
Return Value: true=> If list contains the specified element.
Description: The method ‘contains’ checks if the specified element is present in the list and returns a Boolean value true if the element is present. Otherwise, it returns false.

containsAll

Prototype: boolean containsAll(Collection c)

Parameters: c => Collection to be searched in the list.
Return Value: true=> If all elements in the specified collection are present in the list.
Description: “containsAll” method checks if all the elements present in the specified collection are present in the list. If present it returns a true value and false otherwise.

The following Java program demonstrates the usage of ‘contains’ and ‘containsAll’ methods of the list.

import java.util.*;
public class Main
{
	public static void main(String[] args) {
		//define list of strings
		List<String> list = new ArrayList<String>();
        //initialize list to strings
        list.add("Java");
        list.add("Xml");
        list.add("Python");
        list.add("Ruby");
        list.add("JavaScript");

        //contains method demo
        if(list.contains("C")==true)
            System.out.println("Given list contains string 'C'");
        else if(list.contains("Java")==true)
        System.out.println("Given list contains string 'Java' but not string 'C'");
        
        //containsAll method demo
        List<String> myList = new ArrayList<String>();
        myList.add("Ruby");
        myList.add("Python");
        if(list.containsAll(myList)==true)
            System.out.println("List contains strings 'Ruby' and 'Python'");
        
	}
}

Output:

Given list contains string ‘Java’ but not string ‘C’
List contains strings ‘Ruby’ and ‘Python’

“containsAll” method

equals

Prototype: boolean equals(Object o)

Parameters: o=> The object that is to be tested for equality.
Return Value: true=> If the given object is equal to the list.
Description: This method is used to compare the given object with the list of equality. If the specified object is a list, then the method returns true. Both lists are said to be equal if and only if they are of the same size, and the corresponding elements in the two lists are equal and in the same order.

A demonstration of the equals method is given below:

 import java.util.LinkedList;  
import java.util.List;  

public class Main {  

public static void main(String[] args) {  
        //define lists
        List<Integer> first_list= new LinkedList<>();  
        List<Integer> second_list = new LinkedList<>();
        List<Integer> third_list = new LinkedList<>();
        //initialize lists with values
        for (int i=0;i<11;i++){  
            first_list.add(i); 
             second_list.add(i);  
              third_list.add(i*i);  
        }
        //print each list
        System.out.println("First list: " + first_list);
        System.out.println("Second list: " + second_list);
        System.out.println("Third list: " + third_list);   

//use equals method to check equality with each list to other
if (first_list.equals(second_list) == true)
System.out.println("\nfirst_list and second_list are equal.\n");
else
System.out.println("first_list and second_list are not equal.\n");

if(first_list.equals(third_list))
System.out.println("first_list and third_list are equal.\n");
else
System.out.println("first_list and third_list are not equal.\n");
if(second_list.equals(third_list))
System.out.println("second_list and third_list are equal.\n");
else
System.out.println("second_list and third_list are not equal.\n");
}
}

Output:

Output of equals method

Get

Prototype: Object get(int index)

Parameters: index=> Position at which the element is to be returned.
Return Value: object=> Element at the specified position.
Description: The get() method returns the element at the given position.

This method throws “indexOutOfBoundsException” if the index specified is out of the range of the list.

Set

Prototype: Object set(int index, Object element)

Parameters: index=> Position at which the new element is to be set.
element=> New element to be placed at the position given by index.
Return Value: Object=> Element that was replaced
Description: The method set() replaces the element at the given index by another value given by element.

The method may throw the following exceptions:

UnsupportedOperationException: Set operation is not supported by the List.
ClassCastException: Operation cannot be performed because of the class of the element
IllegalArgumentException: Argument or some aspect of it is illegal
IndexOutOfBoundsException: Index out of range.

The following program shows an example of get () and set() method.

import java.util.*;
public class Main {  

public static void main(String[] args) {  
        //define list
        List listA = new ArrayList();
         listA.add("Java");
        listA.add("C++");
        listA.add("Python");

        //access list elements using index with get () method
        System.out.println("Element at index 0:" + listA.get(0));
        System.out.println("Element at index 1:" + listA.get(1));
        System.out.println("Element at index 2:" + listA.get(2));
        //set element at index 1 to Ruby
        listA.set(1,"Ruby");
        System.out.println("Element at index 1 changed to :" + listA.get(1) );
    }   
}  

Output:

Output of Get and Set method

hashCode

Prototype: int hashCode()

Parameters: NIL
Return Value: int=> hashCode of the list
Description: The method ‘hashCode()’ returns the hashCode of the list which is an integer value.

Example:


import java.util.*;

public class Main
{
	public static void main(String[] args) {
		// Initializing a list of type Linkedlist 
        List<Integer> mylist = new LinkedList<>(); 
        mylist.add(1); 
        mylist.add(3); 
        mylist.add(5);
        mylist.add(7);
        //print the list
        System.out.println("The list:" + mylist); 
        //use hashCode() method to find hashcode of list  
        int hash = mylist.hashCode(); 
  
        System.out.println("Hashcode for list:" + hash); 
    }
} 

Output:

 output of hashcode

isEmpty

Prototype: boolean isEmpty()

Parameters: NIL
Return Value: true=> List is empty
Description: The ‘isEmpty()’ method checks if the list is empty. IsEmpty method is used to check if the list has any elements in it before you begin to process those elements.

indexOf

Prototype: int indexOf(Object o)

Parameters: o=> element to search for in the list
Return Value: int=> the index or position of the first occurrence of the given element in the list. Returns -1 if element is not present.
Description: The method ‘indexOf()’ returns the index of the first occurrence of the given element o in the list. If the element is not found it returns -1.

lastIndexOf

Prototype: int lastIndexOf(Object o)

Parameters: o=> Object whose index is to be searched
Return Value: int=> Index of the last occurrence of the given element in the list, -1 otherwise.
Description: The method ‘lastIndexOf()’ returns the index of the last occurrence of element o in the list. If the element is not found, the method returns -1.

The Java program below demonstrates the usage of indexOf and lastIndexOf methods of the list.

import java.util.*; 
  
public class Main { 
    public static void main(String[] args) 
    { 
        // define an integer array 
        List<Integer> intList = new ArrayList<Integer>(5); 
        //add elements to the list
        intList.add(10); 
        intList.add(20); 
        intList.add(30); 
        intList.add(10); 
        intList.add(20);
        //print the list
        System.out.println("The list of integers:" + intList);
  
        // Use indexOf() and lastIndexOf() methods of list to find first and last index
        System.out.println("first index of 20:"
                           + intList.indexOf(20)); 
        System.out.println("last index of 10:"
                           + intList.lastIndexOf(10)); 
        
    } 
}

Output:

Output of indexOf and lastIndexOf

remove

Prototype: Object remove (int index)

Parameters: index=> Index or position in the list at which the element is to be removed
Return Value: Object=> Element removed
Description: The ‘remove ()’ method removes the element at the given position from the list. After deletion, the elements next to the deleted element are shifted left.

This method may throw the following exceptions:

UnsupportedOperationException: Remove is not supported by the List.
IndexOutOfBoundsException: Index specified is out of range

remove

Prototype: boolean remove(Object o)

Parameters: o=> Element to be removed from the list
Return Value: true=> Element is successfully removed.
Description: This overloaded version of the remove() method removes the first occurrence of a given element o from the list. If the given element is not present in the list, then it remains unchanged.

This method may throw the following exception:

UnsupportedOperationException: Remove is not supported by the List.

removeAll

Prototype: boolean removeAll(Collection c)

Parameters: c=> A collection that contains elements that are removed from the list.
Return Value: true=> If the method call is successful and all the elements specified in the collection c are removed from the list.
Description: The ‘removeAll()’ method is used to remove all the elements from the list that are specified in collection c that is passed as an argument.

This method may throw the following exception:

UnsupportedOperationException: removeAll is not supported by the List.

Let us see an example of remove and removeAll methods.

import java.util.*; 
  
public class Main { 
    public static void main(String[] args) 
    { 
        // Creating a list 
        List<Integer> oddList = new ArrayList<Integer>(); 
        //add elements to the list
        oddList.add(1);
        oddList.add(3);
        oddList.add(5);
        oddList.add(7);
        oddList.add(9);
        oddList.add(11);
        //print the original list
        System.out.println("Original List:" + oddList);
        // Removes element from index 1 
        oddList.remove(1); 
        System.out.println("Oddlist after removing element at index 1:" + oddList);
        
        //removeAll method
        List<Integer> c1 = new ArrayList<Integer>();
        c1.add(1);
        c1.add(5);
        c1.add(11);
        oddList.removeAll(c1);
        System.out.println("Oddlist after removing elements {1,5,11}}:" + oddList);
         
    } 
}

Output:

output of remove method

retainAll

Prototype: boolean retainAll(Collection c)

Parameters: c=> Collection that contains elements that should be retained in the list.
Return Value: true=> If the method call changed the list.
Description: This method removes all the elements from the list except for those which are present in the collection c. In other words, this method retains all the elements in the list that are present in collection c and removes the other elements.

This method may throw the following exception:

UnsupportedOperationException: retainAll is not supported by the List.

import java.util.*; 
  
public class Main { 
    public static void main(String[] args) 
    { 
        // Creating a list 
        List<Integer> oddList = new ArrayList<Integer>(); 
        //add elements to the list
        oddList.add(1);
        oddList.add(3);
        oddList.add(5);
        oddList.add(7);
        oddList.add(9);
        oddList.add(11);
        //print the original list
        System.out.println("Original List:" + oddList);
       
        //retainAll method
        List<Integer> c1 = new ArrayList<Integer>();
        c1.add(1);
        c1.add(5);
        c1.add(11);
        oddList.retainAll(c1);
        System.out.println("Oddlist after call to retainAll (1,5,11):" + oddList);
         
    } 
}
 

Output:

output of retainall

subList

Prototype: List subList (int fromIndex, int toIndex)

Parameters: fromIndex => Lower index of the list (inclusive)
toIndex => Higher index of the list (exclusive)
Return Value: List=> A sub-list of the given list
Description: The method sublist () returns the partial view of the list, also known as sublist from ‘fromIndex’ to ‘toIndex’. The returned sublist is just a view of the parent list and thus any changes made to either list reflect everywhere.

Similarly, all the operations of the list also work on a sublist.

The method can throw the following exception:

IndexOutOfBoundsException: Illegal toIndex value.

An example program for the sublist method is given below.

import java.util.*; 
public class Main { 
    public static void main(String[] args)  { 
        // define a string list 
        List<String> strList = new ArrayList<String>(5); 
        //add elements to the list
        strList.add("Java"); 
        strList.add("Tutorials"); 
        strList.add("Collection"); 
        strList.add("Framework"); 
        strList.add("Series"); 
        //print the original list
        System.out.println("The original list=>strList: " + strList);
        //define another list   
        List<String> subList = new ArrayList<String>(); 
  
        // take a sublist of elements from 2 to 4 from strList 
        subList = strList.subList(2, 4); 
        //print the sublist
        System.out.println("The sublist of strList:" + subList); 
    } 
}
 

Output:

output of sublist method

sort list

Prototype: void sort (Comparator<? super E> c)

Parameters: c=> Comparator on the basis of which the list is sorted.
Return Value: NIL
Description: ‘sort ()’ method is used to sort the list. The method makes use of the comparator specified to sort the list.

Let us see an example of the sort method. We have compared it with the Collections.sort method that sorts the elements in a natural sequence. The output of the program is an ordered list.

import java.util.Collections;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class Main {
	public static void main(String[] args) {
		//define list
		List<Integer> intArray = new ArrayList<>();
		Random random = new Random();
	   	//populate the list with random numbers < 20
		for (int i = 0; i < 10; i++) intArray.add(random.nextInt(20));
		//display the original list
		System.out.println("Original List: "+intArray);
		
		//natural sorting using Collections.sort () method
		Collections.sort(intArray);
		System.out.println("List sorted naturally:\n"+intArray);
		
		//Sorting using list.sort with comparator
		intArray.sort((o1,o2) -> {return (o2-o1);});  //comparator to sort in reverse 
		System.out.println("Reverse List sorted using comparator:\n"+intArray);
	}
}

Output:

output of sort method

toArray

Prototype: Object [] toArray ()

Parameters: NIL
Return Value: Object [] => Array representation of the list
Description: Method toArray() returns the array representation of the list in a proper sequence.

toArray

Prototype: Object[] toArray(Object[] a)

Parameters: a => Array type which is to be matched to list element types while converting the list to an array.
Return Value: Object [] => Array representation of the list.
Description: This overload of method toArray () returns the array containing elements in the list that have the same runtime type as that of array a.

This method may throw the following exception:

ArrayStoreException: The runtime type of every element in the list is not a subtype of the runtime type of every element in this List.

The following is an example of the implementation of the toArray method.

import java.util.*;

public class Main {
   public static void main(String[] args) {
      
    // create list
    ArrayList<String> colorsList = new ArrayList<String>(7);

    // add colors to colorsList
    colorsList.add("Violet");
    colorsList.add("Indigo");
    colorsList.add("Blue");
    colorsList.add("Green");
	colorsList.add("Yellow");
    colorsList.add("Orange");
    colorsList.add("Red");
    System.out.println("Size of the colorsList: " + colorsList.size());

    // Print the colors in the list
    System.out.println("Contents of colorsList:");
    for (String value : colorsList){
      System.out.print(value + " ");
    }  
    
    // Create an array from the list using toArray method
    String colorsArray[] = new String[colorsList.size()];
    colorsArray = colorsList.toArray(colorsArray);
         
   // Display the contents of the array
    System.out.println("\n\nPrinting elements of colorsArray:" + Arrays.toString(colorsArray)); 
    
  }
}

Output:

output of toArray method

Iterator

Prototype: Iterator iterator ()

Parameters: NIL
Return Value: Iterator=> Iterator to iterate over the elements of the list
Description: This method returns the iterator that iterates over the elements in the list.

Java Program to demonstrate using iterator.

import java.util.*;

public class Main {
   public static void main(String[] args) {
      
    // create list
    ArrayList<String> colorsList = new ArrayList<String>(7);

    // add colors to colorsList
    colorsList.add("Violet");
    colorsList.add("Indigo");
    colorsList.add("Blue");
    colorsList.add("Green");
    colorsList.add("Yellow");
    colorsList.add("Orange");
    colorsList.add("Red");
    System.out.println("ColorList using iterator:");
    //define iterator for colorsList
    Iterator<String> iterator = colorsList.iterator();
    //iterate through colorsList using iterator and print each item
    while(iterator.hasNext()){
        System.out.print(iterator.next() + " ");
    }
  }
} 

Output:

Output of iterator method

listIterator

Prototype: ListIterator listIterator()

Parameters: NIL
Return Value: ListIterator=> Listiterator of the elements in the list.
Description: Method listIterator() returns the ListIterator object of the elements in the list. This iterator starts from the beginning of the list i.e. index 0.

listIterator

Prototype: ListIterator listIterator (int index)

Parameters: index=> Position at which listIterator starts.
Return Value: ListIterator=> ListIterator object at specified index in the list.
Description: The overload of method listIterator () returns a listIterator that starts at the given position in the list. The given index indicates that it will be the first element that will be returned by the first call to nextElement() method of ListIterator.

The method may throw IndexOutOfBoundsException for the invalid value of the index.

The following example demonstrates listIterator usage.

import java.util.*;

public class Main {
  public static void main(String[] args)   {
    	//define list & add items to list
	List<String> nameList = new LinkedList<>();
	nameList.add("Java");
	nameList.add("C++");
	nameList.add("Python");
	// get listIterator for the list
	ListIterator<String> namesIterator = nameList.listIterator();
	
	// Traverse list using listiterator and print each item
	System.out.println("Contents of list using listIterator:");
	while(namesIterator.hasNext()){
	   System.out.print(namesIterator.next() + " ");			
	}	
  }
} 

Output:

Output of listIterator method

We will discuss ListIterator in detail later.

Let’s now discuss some of the miscellaneous operations that can be done on lists but methods for which are not provided in the list interface.

Copy List In Java

For copying elements of one list to another list, you have to use the copy() method provided by the Collections framework.

The method Collections.copy() copies all the elements of the list provided as the second argument, to the list provided as the first argument. Note that the list to which the contents of another list are being copies should be large enough to accommodate the copied elements.

If the list is not large enough, the copy method throws “indexOutOfBoundsEexception”.

The following program copies the contents of one list to another.

import java.util.*;
public class Main {
   public static void main(String[] args) {
    //create first ArrayList object
    List aList_1 = new ArrayList();
   
    //Add elements to first ArrayList
    aList_1.add("R");
    aList_1.add("G");
    aList_1.add("B");
    //print the List
    System.out.println("The first list:" + aList_1);
   
    //create second ArrayList object
    List aList_2 = new ArrayList();
    
    //Add elements to second Arraylist
    aList_2.add("Red");
    aList_2.add("Green");
    aList_2.add("Blue");
    aList_2.add("Yellow");
    aList_2.add("Brown");
   
    System.out.println("The second list: " + aList_2);
   
    //use Collections.copy() method to copy elements of first list to second list.
    Collections.copy(aList_2,aList_1);
   
    //print the resultant second Arraylist
    System.out.println("\n\nThe second list after copying first list to second list: " + aList_2);   
  }
}
 

Output:

Output of Copy List method

Remove Duplicates From A List In Java

A given list may or may not have repetitive elements or duplicates. If the list you are working with has duplicate elements and you want all distinct elements in the list, then there are two methods to remove duplicates from the list supported in Java.

Using Java 8 stream

The first method to remove duplicates from the list is by using the distinct () method provided by Java 8 stream. Here, the list containing duplicates invokes the stream ().distinct method and then the return value is converted to a new list which will have only the distinct elements.

The following program demonstrates the usage of the distinct () method.

import java.util.*;
import java.util.stream.Collectors; 
class Main 
{ 
    public static void main(String[] args) 
    { 
        // original list 
        List<Integer> intlist = new ArrayList<>( 
            Arrays.asList(1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5,6,5,3,4)); 
        // Print the list 
        System.out.println("Original ArrayList: "
                           + intlist); 
  
        // using distinct() method of Java 8 stream remove duplicates from original List
        //and generate a new list without duplicates
        List<Integer> distinct_list = intlist.stream().distinct() 
                                      .collect(Collectors.toList()); 
  
        // Print the new list 
        System.out.println("ArrayList after removing duplicates: "
                           + distinct_list); 
    } 
}
 

Output:

Output of Java 8 stream

Using Iterator approach

Removing duplicates from the list using the iterator is a lengthy and primitive approach. In this approach, you have to traverse through the list and put the first occurrence of every element in a new list. Every subsequent element is checked if it’s a duplicate.

The program below achieves this.

import java.util.*; 
  
public class Main { 
      public static void main(String args[]) 
    { 
         // create original list
        ArrayList<Integer> aList = new ArrayList<>(
            Arrays.asList(1, 1, 1, 2, 2, 3, 3, 3, 4, 5, 5, 6, 5, 3, 4)); 
  
        // Print the original list 
        System.out.println("Original List: "+ aList); 
  
        // Create a new list 
        ArrayList<Integer> new_List = new ArrayList<>(); 
  
        // Traverse through the original list to remove duplicates 
        for (Integer element : aList) { 
              // check if element is present in new_List, else add it 
            if (!new_List.contains(element)) { 
                  new_List.add(element); 
            } 
        } 
        // Print the new list without duplicates 
        System.out.println("List after removing duplicates: "+ new_List); 
    } 
}
 

Output:

Output Using Iterator Approach

Frequently Asked Questions

Q #1) What is get method in the list in Java?

Answer: Get method of the list is used to retrieve a particular element in the list based on the index. You pass the required index to the get method and the get method will return the element value at that index.

Q #2) What is the toArray method in Java?

Answer: The method toArray () is used to get the array representation of the list.

Q #3) How do you sort a list in Java?

Answer: In Java, a list can be sorted using the sort method of the list. You can pass your own sorting criteria using the comparator interface that is passed to the sort method as a parameter.

You can also use Collections. Sort method to sort the list. This method sorts the list as per natural ordering.

Q #4) What is Arrays.asList() in Java?

Answer: The method ‘asList’ of array returns the list of elements backed by an array.

Conclusion

In this tutorial, we have learned all the methods that a list provides. The Java list provides various methods using which you can manipulate and process lists including searching, sorting, etc. We have explained each method with appropriate programming examples here.

In our upcoming tutorial, we will discuss the ListIterator in detail.

=> Explore The Simple Java Training Series Here.

Was this helpful?

Thanks for your feedback!

Leave a Comment