

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do you make a list iterator in Java?
We can utilize listIterator() method of List interface, which allows element insertion and replacement, and bidirectional access in addition to the normal operations that the Iterator interface provides.
Syntax
ListIterator<E> listIterator()
Returns a list iterator over the elements in this list (in proper sequence).
Example
Following is the example showing the usage of listIterator() method −
package com.tutorialspoint; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.ListIterator; public class CollectionsDemo { public static void main(String[] args) throws CloneNotSupportedException { List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4,5)); System.out.println(list); ListIterator<Integer> iterator = list.listIterator(); // Modify the list using listIterator while(iterator.hasNext()){ Integer item = iterator.next(); iterator.set(item * item); } System.out.println(list); // Removal of element is allowed iterator = list.listIterator(); while(iterator.hasNext()){ Integer item = iterator.next(); if(item % 2 == 0) { iterator.remove(); } } System.out.println(list); // Addition of element is allowed iterator = list.listIterator(); while(iterator.hasNext()){ Integer item = iterator.next(); if(item % 5 == 0) { iterator.add(36); } } System.out.println(list); } }
Output
This will produce the following result −
[1, 2, 3, 4, 5] [1, 4, 9, 16, 25] [1, 9, 25] [1, 9, 25, 36]
- Related Questions & Answers
- How do you make a shallow copy of a list in Java?
- How do you copy a list in Java?
- How do you create a list in Java?
- How do you create a list with values in Java?
- How do you create a list from a set in Java?
- How do you turn a list into a Set in Java?
- How to iterate a Java List using Iterator?
- How do you convert list to array in Java?
- How do you create an empty list in Java?
- How do you add an element to a list in Java?
- How do you check a list contains an item in Java?
- How do you make code reusable in C#?
- Convert an Iterator to a List in Java
- How to iterate List using Iterator in Java?
- How do you make a string in PHP with a backslash in it?
Advertisements