In this tutorial, we will learn convert iterator to list in java
Here we are giving two approach to convert iterator to list in java
Syntax in Java 8
ArrayList<String> list = new ArrayList<String>();
iterator.forEachRemaining(list::add);
Syntax in Java 7
ArrayList<String> list = new ArrayList<String>();
while (iterator.hasNext()) {
String string = (String) iterator.next();
list.add(string);
}
Example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
public class IteratorToList {
public static void main(String[] args) {
Iterator<String> iterator = Arrays.asList("Rajesh", "Kumar", "Beginners", "Bug").iterator();
convertToListJava7(iterator);
convertToListJava8(iterator);
}
/**
* Java 7 Approach
*
* @param iterator
* @return
*/
public static ArrayList<String> convertToListJava7(Iterator<String> iterator) {
ArrayList<String> list = new ArrayList<String>();
while (iterator.hasNext()) {
String string = (String) iterator.next();
list.add(string);
}
return list;
}
/**
* Java 8 Apporach
*
* @param iterator
* @return
*/
public static ArrayList<String> convertToListJava8(Iterator<String> iterator) {
ArrayList<String> list = new ArrayList<String>();
iterator.forEachRemaining(list::add);
return list;
}
}
Github
Related Articles
Iterate list using streams in java