Java Lists

The List class in Java allows you to keep an ordered collection. It has index-based techniques for inserting, updating, deleting, and searching elements. It may also contain redundant elements. The null elements can also be stored in the list.

The Collection interface is inherited by the List interface, located in java.util package. It’s a ListIterator interface factory. We can iterate the list forward and backward using the ListIterator. ArrayList, LinkedList, Stack, and Vector are the List interface, implementation classes. In Java programming, the ArrayList and LinkedList are commonly utilized. Since Java 5, the Vector class has been deprecated.

Interface declarations in a list

public interface List extends Collection

List methods in Java

  • void add(int index, E element) -helps insert the specified element at the given position in a list.
  • boolean add(E e)- It is used to append the specified element at the end of a list.
  • boolean addAll(Collection c) – It is used to append all items in the given collection to the lists’ end.
  • boolean addAll(int idx, Collection c) – It is used to append all the elements in the specified collection, starting at the specified position of the list.
  • void clear()- It is used to remove all elements from this list.
  • boolean equals(Object o)- It is used to compare the specified object with the elements of a list.
  • int hashcode() – It returns the hash code value for a list.
  • E get(int index)- It is used to fetch the element from the particular position of the list.
  • boolean isEmpty()- It returns true if the list is empty, otherwise false.
  • int lastIndexOf(Object o)- It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.
  • Object[] toArray()- It is used to return an array containing all of the elements in this list in the correct order.
  • T[] toArray(T[] a)- It is used to return an array containing all of the elements in this list in the correct order.
  • boolean contains(Object o)- It returns true if the list contains the specified element.
  • boolean containsAll(Collection c)- It returns true if the list contains all the specified element.
  • int indexOf(Object o) – It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.
  • E remove(int index)- It removes the element present at the specified position in the list.
  • boolean remove(Object o)- It is used to remove the first occurrence of the specified element.
  • boolean removeAll(Collection c)- It is used to remove all the elements from the list.
  • void replaceAll(UnaryOperator operator)- It replaces all the elements from the list with the specified element.
  • void retainAll(Collection c)- It is used to retain all the elements in the list present in the specified collection.
  • E set(int index, E element) is used to replace the specified element in the list, present at the specified position.
  • void sort(Comparator c) – It is used to sort the elements of the list based on a specified comparator.
  • Spliterator spliterator() is used to create a spliterator over the elements in a list.
  • List subList(int fromIndex, int toIndex) – It is used to fetch all the elements within the given range.
  • int size()- It returns the number of elements present in the list.

ArrayList vs. Java List

ArrayList is the implementation class of List, which is an interface.

How to make a List

Let’s go over how to make objects or instances in a List class. Objects of the type list cannot be created since List is an interface. We always require a class that implements this List to build an object. Furthermore, since the introduction of Generics in Java 1.5, it is also possible to limit the object put in a List. The list is an ‘interface’ implemented by the ArrayList class, pre-defined in java.util package, just as several other user-defined ‘interfaces’ implemented by user-defined ‘classes.’

The List interface is implemented by the ArrayList and LinkedList classes. Let’s examine a few instances of how to make a List:

// Making use of ArrayList to create a List of type String
List stringList=new ArrayList();

//using ArrayList in creation of a List of type Integer
List integerList=new ArrayList();

//Creating a List of type Employee using ArrayList
List employeeList=new ArrayList();

//Creation of String a List using LinkedList
List linkedList=new LinkedList();

In a nutshell, you can make any List. The types are specified using the ArrayList<T> and LinkedList<T> classes. The letter T stands for type.

Example of a Java List

Let’s look at a simple List example that uses the ArrayList class as the implementation.

ublic static void main(String args[]){
  
//Creating a List
List programmingLanguages=new ArrayList();
  
//Adding elements in the List
programmingLanguages.add("Java");
programmingLanguages.add("Python");
programmingLanguages.add("JavaScript");
programmingLanguages.add("Angular");
  
//Iterating the List element using for-each loop
for(String languages:programmingLanguages)
System.out.println(languages);
  
}
}

How can you change an Array to a List?

By traversing the array and adding each element to the list one by one, we can transform the array into a list.
add() is a method for adding items to a list. Let’s look at an example of converting array elements to List.

import java.util.*;

public class exampleArrayToList{
  
  public static void main(String args[]){
    
    //Creating Array
  	String[] programmingLanguages={"Java","JavaScript","Kotlin","Scala"};
  	System.out.println("Printing Array: "+Arrays.toString(programmingLanguages));
    
    // Array to List Conversion
    List languagesList=new ArrayList();
    for(String lang:programmingLanguages){
    languagesList.add(lang);
}
System.out.println("Programming Languages List: "+languagesList);
    
}
}

How can I make a List into an Array?

The list.toArray() method converts a List to an Array. Let’s look at a quick example of converting list elements to arrays.

import java.util.*;

public class exampleListToArray{
  
  static void main(String args[]){
  List companiesList = new ArrayList<>();
  companiesList.add("Microsoft");
  companiesList.add("Google");
  companiesList.add("Apple");
  companiesList.add("HP");
    
  // ArrayList to Array Conversion
String[] companiesArray = companiesList.toArray(new String[companiesList .size()]);
System.out.println("Array of Companies: "+Arrays.toString(companiesArray));
System.out.println("List of Companies: "+companiesList);
}
}

Let us now use the List Interface to execute various operations to understand it better. We’ll discuss the operations listed below and then implement them using clean Java code.

Operations on a List interface

Because List is an interface, it is used with a class that implements it. Let’s look at using the List to accomplish a few everyday operations.

  • Operation 1: Using the add() function to add entries to the List class
  • Operation 2: Using the set() function to update members in the List class
  • Operation 3: Using the remove() function to delete elements

Now let’s break down each operation and see how we may implement it in the code to understand it better.

Using the add() function to add entries to the List class

The add() method adds a new element to the list. The latter method is overloaded with the capability to accomplish several operations based on various arguments.

Parameters

It requires two parameters as follows:

  • add(Object): This method adds a new element to the List’s end.
  • add(int index, Object): This method adds an element to the List at a given index.
// Java Program that Adds Elements to a List
// Importing all utility classes

import java.util.*;

// Main class
class listIntefaceClass {

public static void main(String args[])
{
    // Creation of an object of List interface, implemented by ArrayList class
    List<String> codeLanguages = new ArrayList<>();

    // Adding elements to object of List interface
    // Custom elements
    codeLanguages.add("Django");
    codeLanguages.add("Flask");
    codeLanguages.add(1, "Bottle");

    // Printing every elements inside the List interface object
    System.out.println(codeLanguages);
}
}

Updating elements

Because List is indexed, the element we want to modify is referenced by the element’s index. As a result, it requires an index and the modified element to be inserted at that index. If we want to update an element after it has been added, we can use the set() method.

// Java Program for Updating List Elements

// Importing utility classes
import java.util.*;

// Main class
class listIntefaceClass {

	// Main driver method
	public static void main(String args[])
	{
		// Creating an object of List interface
		List<String> codeLanguages = new ArrayList<>();

		// Adding elements to object of List class
		codeLanguages.add("Django");
		codeLanguages.add("Flask");
		codeLanguages.add(1, "Bottle");

		// Display theinitial elements in List
		System.out.println("Initial ArrayList " + al);

		//  use set() to update element at 1st index
		codeLanguages.set(1, "Python");

		// finally Print and display the new updated List
		System.out.println("Updated ArrayList is : " + codeLanguages);
	}
}

Removing Elements

The remove() function is responsible for deleting an element from a List. This method is overloaded with the ability to do several operations based on various arguments. They are as follows:

Parameters:

remove(Object): The remove(Object) method is used to delete an object from a List. If there are numerous instances of the same item, the first one is eliminated.

Because a List is indexed, remove(int index) takes an integer value that eliminates the element at that precise index in the List. After removing one element, all other elements are moved to the left to cover the space, and the object indices are updated.

// Java Program for Removing Items from a List

// Importing List and ArrayList classes
// from java.util package
import java.util.ArrayList;
import java.util.List;

// Main class
class listIntefaceClass {

	public static void main(String args[])
	{

		// Creating List class object
		List<String> codeLanguages = new ArrayList<>();

		// Adding elements to the object
		// Custom inputs
		codeLanguages.add("Django");
		codeLanguages.add("Django");
		codeLanguages.add(1, "Bottle");

		// Adding For at 1st indexes
		codeLanguages.add(1, "Python");

		// Printing the initial ArrayList
		System.out.println("The Initial ArrayList is: " + codeLanguages);

		// remove  theelement from the above list that is present at 1st index
		codeLanguages.remove(1);

		// Print the List after removal of the element
		System.out.println("After the Index Removal: " + codeLanguages);

		// Now remove the current object from the updated
		// List
		codeLanguages.remove("Django");

		// Finally, print the updated List now
		System.out.println("After the Object Removal "+ codeLanguages);
	}
}

Get and Set List Element

The get() method retrieves the element at the specified index, whereas the set() method modifies or replaces it.

import java.util.*;
 
public class exampleGetSetList{  
 public static void main(String args[]){  
 // List  Creation
 List<String> subjectList=new ArrayList<String>();  

 //Addition of elements to the List  
 subjectList.add("Databases");  
 subjectList.add("Machine Learning");  
 subjectList.add("Data Structures & Algorithms");  
 subjectList.add("Operating Systems");  

 //illustrating how to access an element    
 System.out.println("Returning element: "+subjectList .get(1));//it will return the 2nd element, because index starts from 0  

 //illustrating how to change the element  
 subjectList.set(1,"Dates");  

 //Iterating the Subject List elements using for-each loop  
 for(String subjects:subjectList)  
  System.out.println(subjects);  
  
 }  
}

Sorting a List

There are various methods for sorting a List; in this case, we’ll utilize the Collections.sort() method to sort the list element. Collections is a utility class in java.util package that has the static method sort(). We may quickly sort any List with the Collections.sort() function.

import java.util.*;  
class exampleSortingArrayList{  
 public static void main(String args[]){  

  //Creation of a list containing subjects for students to choose from  
  List<String> subjectList=new ArrayList<String>();  
  subjectList.add("Data Structures & Algorithms");  
  subjectList.add("Databases");  
  subjectList.add("Machine Learning");  
  subjectList.add("Introduction to computers");  

  // illustrating sorting the subjects list  
  Collections.sort(subjectList);  

   //illustrating traversing the subject list using for-each loop  
  for(String subj:subjectList)  
    System.out.println(subj);  
      
 System.out.println("Demonstrating how to sorting numbers");  

  //Creating a list of numbers  
  List<Integer> numberList=new ArrayList<Integer>();  
  numberList.add(59);  
  numberList.add(12);  
  numberList.add(98);  
  numberList.add(33);  

  //illustrating sorting the number list  
  Collections.sort(numberList);  

   // illustrating subject traversal using the for-each loop  
  for(Integer num:numberList)  
    System.out.println(num);  
 }  
   
}  

Interface for a Java ListIterator

The ListIterator interface is used to backward and forward traverse the element.

Declaration of the ListIterator interface

public interface ListIterator extends Iterator

ListIterator Interface Methods in Java

  • void add(E e) – This method inserts the specified element into the list.
  • boolean hasNext()- It returns true if the list iterator has more elements while traversing the list in the forward direction.
  • E next() – This method returns the next element in the list and advances the cursor position.
  • int nextIndex()- This method returns the index of the element that would be returned by a subsequent call to next()
  • boolean hasPrevious()- This method returns true if the iterator has more elements while traversing the list in the reverse direction.
  • E previous()- This method returns the last element in the list and moves the cursor position backward.
  • E previousIndex()- This method returns the index of the element returned by a subsequent call to previous().
  • void remove() – This method removes the last element from the list that was returned by next() or previous() methods
  • void set(E e) – This method replaces the last element returned by next() or previous() methods with the specified element.

ListIterator Interface Example

import java.util.*;  

public class exampleListIterator{  
public static void main(String args[]){  

List<String> citiesList =new ArrayList<String>();    
        citiesList.add("New York");    
        citiesList.add("London");    
        citiesList.add("Los Angeles");    
        citiesList.add("Daka");    

        ListIterator<String> listIterator=al.listIterator();    
        System.out.println("Elements Traversal in forward direction");    
        while(listIterator .hasNext()){    
              
        System.out.println("index is:"+listIterator .nextIndex()+" value is:"+listIterator .next());    
        }    
        System.out.println("Elements Traversal in backward direction");    
        while(listIterator .hasPrevious()){    
          
        System.out.println("index is:"+listIterator .previousIndex()+" value:"+listIterator .previous());    
        }    
}  
}  

Employee as an example of a list

Let’s look at an example of a list where we’re adding Employees.

import java.util.*;  
class Employee {  
int id;  
String firstname,lastname,gender;  
int age;  
public Employee(int id, String firstname, String lastname, String gender, int age) {  
    this.id = id;  
    this. firstname = firstname;  
    this. lastname = lastname;  
    this. gender = gender;  
    this. age = age;  
}  
}  
public class exampleLis {  
public static void main(String[] args) {  
    //Creating list of Employees  
    List<Employee> employeesList=new ArrayList<Employee>();  

    //Creating Employees  
    Employee empOne=new Employee(10,"Thompson","Yale","Male",18);  
    Employee empTwo=new Employee(20,"Ann","Forouz","Female",14);  
    Employee empThree=new Employee(30,"Jerry ","Tom","Male",16);  

    //Adding Employee to list  

    employeesList.add(empOne);  
    employeesList.add(empTwo);  
    employeesList.add(empThree);  

    //Employee List Traversal  
    for(Employee emp:employeesList){  
    System.out.println(emp.id+" "+emp.name+" "+emp.author+" "+emp.publisher+" "+emp.quantity);  
    }  
}  
}  

Conclusion

The List interface is used to keep track of the collection’s order. It is a Collection’s child interface. In addition, it’s a sorted collection of objects that can store duplicate values. The list supports positional access and insertion of members because the insertion order is preserved.

Similar Posts

Leave a Reply

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