Java Iterator create Random Iterator

Description

Java Iterator create Random Iterator

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

class RandomIterator<T> implements Iterator<T> {
  private final Iterator<T> iterator;

  public RandomIterator(Iterator<T> i) {
    final List<T> items;

    items = new ArrayList<T>();

    while (i.hasNext()) {
      final T item;

      item = i.next();//from   ww w .  jav a2  s .  c  om
      items.add(item);
    }

    Collections.shuffle(items);
    iterator = items.iterator();
  }

  public boolean hasNext() {
    return (iterator.hasNext());
  }

  public T next() {
    return (iterator.next());
  }

  public void remove() {
    iterator.remove();
  }
}

public class Main {
  public static void main(final String[] args) {
    List<String> items = Arrays.asList("CSS","HTML","Java","Javascript","SQL","HTML5");

    Iterator<String> iterator = new RandomIterator<String>(items.iterator());

    while (iterator.hasNext()) {
      String item = iterator.next();
      System.out.println(item);
    }
  }
}



PreviousNext

Related