All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.bbn.bue.common.collections.ShufflingIterable Maven / Gradle / Ivy

There is a newer version: 4.1.2
Show newest version
package com.bbn.bue.common.collections;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * This is an {@link Iterable} which provides its data in a random order
 * every time an iterator is requested. Note this must its entire underlying
 * {@link Iterable} into memory.
 * @param 
 */
public final class ShufflingIterable implements Iterable {
  private final ImmutableList data;
  private final Random rng;

  private ShufflingIterable(Iterable iterable, Random rng) {
    this.data = ImmutableList.copyOf(iterable);
    this.rng = checkNotNull(rng);
  }

  public static  ShufflingIterable from(Iterable iterable, Random rng) {
    return new ShufflingIterable(iterable, rng);
  }

  @Override
  public Iterator iterator() {
    final List shuffledList = Lists.newArrayList(data);
    Collections.shuffle(shuffledList);
    return Collections.unmodifiableList(shuffledList).iterator();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy