- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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]
Advertisements