Java Lists (with examples) | Code Underscored

0
79

The List Department in Java allows you to keep a neat collection. It has index-based techniques for inserting, updating, deleting and searching for elements. It may also contain unnecessary elements. You can also store the null components in the list.

The collection interface is inherited by the List interface, located in the java.util package. It’s a ListIterator interface factory. We can repeat the list back and forth using ListIterator. ArrayList, LinkedList, Stack, and Vector are List Interface, application classes. In Java programming, ArrayList and LinkedList are in common use. Since Java 5, the Vector class has been deprecated.

Interface statements in the list

public interface List extends Collection

List of methods in Java

  • void add (int index, E element) – Helps to insert the specified element in the given position in the list.
  • boolean add (E e) – It is used to add the specified element at the end of a list.
  • boolean addAll (Collection c) – is used to add all the items in the given collection to the end of the lists.
  • boolean addAll (int idx, Collection c) – It is used to add all the elements in the specified collection, starting from the location specified in the list.
  • void clear () – is used to remove all components from this list.
  • boolean equals (Object o) – is used to compare the specified object with the elements of a list.
  • int hashcode () – returns the hash code value for a list.
  • E get (int index) – It is used to get the element from the particular position of the list.
  • boolean isEmpty () – returns true if the list is empty, otherwise false.
  • int lastIndexOf (Object o) – is used to return the index in this list of the last instance of the specified element, or -1 if the list does not contain this element.
  • resist[] toArray () – is used to return an array that contains all the elements in this list in the correct order.
  • ninth[] toArray (T[] A) – It is used to return an array containing all the elements in this list in the correct order.
  • boolean contains (Object o) – returns true if the list contains the specified element.
  • boolean containsAll (Collection c) – This returns true if the list contains all the specified elements.
  • int indexOf (Object o) – is used to return the index in this list of the first appearance of the specified element, or -1 if the list does not contain this element.
  • E remove (int index) – This removes the existing element at the location specified in the list.
  • boolean remove (Object o) – is used to remove the first instance of the specified element.
  • boolean removeAll (Collection c) – is used to remove all components from the list.
  • void replaceAll (UnaryOperator) – it replaces all the elements from the list with the specified element.
  • void retainAll (Collection c) – is used to preserve all the items in the list that exist in the specified collection.
  • E set (int index, E element) is used to replace the element specified in the list, which exists in the specified location.
  • void sort (Comparator c) – It is used to sort the list components based on a specified comparator.
  • Spliterator Spliterator () is used to create a splitter over the elements in the list.
  • List subList (int fromIndex, int toIndex) – It is used to bring all the elements in the given range.
  • int size () – it returns the number of existing elements in the list.

ArrayList vs. Java List

ArrayList is List’s application class, which is an interface.

How to make a list

Let’s go over how to create objects or instances in the List class. You cannot create objects of type List because List is an interface. We always require a class that applies this list to build an object. Moreover, since the launch of Generics in Java 1.5, it is also possible to restrict the object inserted into the list. The list is an ‘interface’ implemented by the ArrayList class, predefined in the java.util package, just like some other user-defined ‘interfaces’ implemented by user-defined ‘classes’.

The List interface is implemented by the ArrayList and LinkedList departments. Let’s look at some cases of how to create 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 short, you can make any list. The types are defined using the ArrayList classes And LinkedList. The letter T represents a type.

Example of a Java list

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

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 do I change an array to a list?

By moving the array and adding each element to the list one by one, we can turn the array into a list.
add () is a method of adding items to a list. Let’s look at an example of converting array components to a 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 do I turn 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 perform various actions to better understand it. We will discuss the steps listed below and then implement them using clean Java code.

Actions on a list interface

Because List is an interface, it is used with a class that implements it. Let’s take a look at using the list to perform some daily operations.

  • Action 1: Use the add () function to add values ​​to the List class
  • Action 2: Use the set () function to update members in the List class
  • Action 3: Use the remove () function to delete elements

We will now unpack each action and see how we can implement it in the code to better understand it.

Use the add () function to add values ​​to the List class

The add () method adds a new element to the list. The latter method is loaded with the ability to perform a number of actions based on various arguments.

Parameters

It requires two parameters as follows:

  • add (Object): This method adds a new element to the end of the list.
  • add (int index, Object): This method adds an element to a list in 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);


Update elements

Because List is indexed, the element we want to change is redirected by the element’s index. As a result, it requires the addition of an index and the odd element in that index. If we want to update an element after adding it, 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);
	

Removal of elements

The remove () function is responsible for deleting an impressive element. This method is loaded with the ability to perform a number of actions based on different arguments. They are as follows:

Parameters:

remove (Object): The remove (Object) method is used to delete an impressive object. If there are many instances of the same item, the first is canceled.

Because a list is added to an index, remove (int index) takes an entire value that eliminates the element in that exact 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 up a list element

The get () method retrieves the element in the specified index, while 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);  
  
   

Sort list

There are different methods for sorting a list; In this case, we will use the Collections.sort () method to sort the list element. Collections is a service class in the java.util package that has the static sort () method. We may quickly sort each 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 Java ListIterator

The ListIterator interface is used to go back and forth of the element.

ListIterator interface statement

public interface ListIterator extends Iterator

ListIterator interface methods in Java

  • void add (E e) – This method adds the specified element to the list.
  • boolean hasNext () – returns true if the list iterator has more elements while crossing 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 to be returned in a subsequent reading to next ()
  • boolean hasPrevious () – This method returns true if the iterator has more elements while crossing the list in the opposite direction.
  • E previous () – This method returns the last element in the list and moves the cursor position backwards.
  • E previousIndex () – This method returns the index of the returned element in a subsequent reading to the previous ().
  • void remove () – This method removes the last element from the list 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.

Example of the ListIterator interface

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());    
            
  
  

Works as an example list

Let’s look at an example list where we add 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);  
      
  
  

Summary

The List interface is used to track the order of the collection. This is a child interface of a collection. In addition, it is a sorted collection of objects that can store duplicate values. The list supports local access and adding members because the income order is maintained.

Source

LEAVE A REPLY

Please enter your comment!
Please enter your name here