Wednesday, 11 March 2020

Convert iterator to list

Approach 1: By traversing through the iterator.
private static <T> List<T> getList_approach1(Iterator<T> iterator) {
 if (iterator == null) {
  return Collections.EMPTY_LIST;
 }

 List<T> list = new ArrayList<>();

 while (iterator.hasNext()) {
  list.add(iterator.next());
 }

 return list;

}

Approach 2: Using iterator.forEachRemaining method.
private static <T> List<T> getList_approach2(Iterator<T> iterator) {
 if (iterator == null) {
  return Collections.EMPTY_LIST;
 }

 List<T> list = new ArrayList<>();
 iterator.forEachRemaining(list::add);

 return list;
}

Approach 3: Using Streams.
private static <T> List<T> getList_approach3(Iterator<T> iterator) {
 if (iterator == null) {
  return Collections.EMPTY_LIST;
 }

 return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
   .collect(Collectors.toCollection(ArrayList::new));
}

Find the below working application.

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

public class App {

 private static <T> List<T> getList_approach1(Iterator<T> iterator) {
  if (iterator == null) {
   return Collections.EMPTY_LIST;
  }

  List<T> list = new ArrayList<>();

  while (iterator.hasNext()) {
   list.add(iterator.next());
  }

  return list;

 }

 private static <T> List<T> getList_approach2(Iterator<T> iterator) {
  if (iterator == null) {
   return Collections.EMPTY_LIST;
  }

  List<T> list = new ArrayList<>();
  iterator.forEachRemaining(list::add);

  return list;
 }

 private static <T> List<T> getList_approach3(Iterator<T> iterator) {
  if (iterator == null) {
   return Collections.EMPTY_LIST;
  }

  return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
    .collect(Collectors.toCollection(ArrayList::new));
 }

 private static <T> void printList(List<T> list) {
  for (T obj : list) {
   System.out.print(obj + " ");
  }

  System.out.println("\n");
 }

 public static void main(String[] args) {
  List<Integer> list = Arrays.asList(2, 3, 5, 7);

  List<Integer> list1 = getList_approach1(list.iterator());
  List<Integer> list2 = getList_approach2(list.iterator());
  List<Integer> list3 = getList_approach2(list.iterator());

  printList(list1);
  printList(list2);
  printList(list3);
 }

}

Output
2 3 5 7

2 3 5 7

2 3 5 7


You may like

No comments:

Post a Comment