Java ListIterator hasPrevious() Method Tutorial

In this section, we will learn what the ListIterator hasPrevious() method is and how to use it in Java.

What is ListIterator hasPrevious() Method in Java?

When traversing a collection object using a ListIterator object in a reverse direction, we can use the `hasPrevious()` method to see if there’s still an element to be returned from the list or not.

ListIterator hasPrevious() Method Syntax:

boolean hasPrevious()

ListIterator hasPrevious() Method Parameters

The method does not take an argument.

ListIterator hasPrevious() Method Return Value

The return value of this method is of type Boolean.

If there is still an element to be returned from the list, this method returns true. Otherwise the value false will be returned.

ListIterator hasPrevious() Method Exception:

The method does not throw an exception.

Example: using ListIterator hasPrevious() Method in Java

import java.util.List;
import java.util.ArrayList;
import java.util.ListIterator;
public class Main {

    public static void main(String[] args){
        
        List<String> list = new ArrayList<>();
        list.add("Omid");
        list.add("Jack");
        list.add("Ellen");
        list.add("John");

        ListIterator<String> iterate = list.listIterator();

        while(iterate.hasNext()){
         iterate.next();
        }
        while(iterate.hasPrevious()){
         System.out.println(iterate.previous());
        }
    }
}

Output:

John

Ellen

Jack

Omid

Leave a Reply