Example usage for java.util Collections shuffle

List of usage examples for java.util Collections shuffle

Introduction

In this page you can find the example usage for java.util Collections shuffle.

Prototype

public static void shuffle(List<?> list) 

Source Link

Document

Randomly permutes the specified list using a default source of randomness.

Usage

From source file:com.haulmont.cuba.core.sys.remoting.ClusterInvocationSupport.java

public void init() {
    urls = new ArrayList<>();
    String[] strings = baseUrl.split("[,;]");
    for (String string : strings) {
        if (!StringUtils.isBlank(string)) {
            urls.add(string + "/" + servletPath);
        }//from  w ww . j  av a2  s.c o  m
    }
    if (urls.size() > 1 && randomPriority) {
        Collections.shuffle(urls);
    }
}

From source file:com.gs.collections.impl.jmh.AggregateByTest.java

@Before
@Setup(Level.Iteration)//  w  ww .j a  v a2  s . c  om
public void setUp() {
    this.executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    Collections.shuffle(this.gscPositions);
    Collections.shuffle(this.jdkPositions);
}

From source file:com.anhth12.lambda.ml.param.HyperParams.java

public static List<List<?>> chooseHyperParameterCombos(Collection<HyperParamValues<?>> ranges, int howMany,
        int perParam) {
    Preconditions.checkArgument(howMany > 0);
    Preconditions.checkArgument(perParam >= 0);

    int numParams = ranges.size();
    if (numParams == 0 || perParam == 0) {
        return Collections.<List<?>>singletonList(Collections.emptyList());
    }/* w ww .ja v  a  2  s  . com*/

    // Put some reasonable upper limit on the number of combos
    Preconditions.checkArgument(Math.pow(perParam, numParams) <= MAX_COMBOS);

    int howManyCombos = 1;
    List<List<?>> paramRanges = new ArrayList<>(numParams);
    for (HyperParamValues<?> range : ranges) {
        List<?> values = range.getTrialValues(perParam);
        paramRanges.add(values);
        howManyCombos *= values.size();
    }

    List<List<?>> allCombinations = new ArrayList<>(howManyCombos);
    for (int combo = 0; combo < howManyCombos; combo++) {
        List<Object> combination = new ArrayList<>(numParams);
        for (int param = 0; param < numParams; param++) {
            int whichValueToTry = combo;
            for (int i = 0; i < param; i++) {
                whichValueToTry /= paramRanges.get(i).size();
            }
            whichValueToTry %= paramRanges.get(param).size();
            combination.add(paramRanges.get(param).get(whichValueToTry));
        }
        allCombinations.add(combination);
    }

    if (howMany >= howManyCombos) {
        Collections.shuffle(allCombinations);
        return allCombinations;
    }
    RandomDataGenerator rdg = new RandomDataGenerator(RandomManager.getRandom());
    int[] indices = rdg.nextPermutation(howManyCombos, howMany);
    List<List<?>> result = new ArrayList<>(indices.length);
    for (int i = 0; i < indices.length; i++) {
        result.add(allCombinations.get(i));
    }
    Collections.shuffle(result);
    return result;
}

From source file:aj.com.watchandshare.MainFragment.java

private void loadRows() {
    List<Movie> list = MovieList.setupMovies();

    mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
    mCardPresenter = new CardPresenter();

    int i;//ww  w . jav  a 2  s . c  o  m
    for (i = 0; i < NUM_ROWS; i++) {
        if (i != 0) {
            Collections.shuffle(list);
        }
        ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter);
        for (int j = 0; j < NUM_COLS; j++) {
            listRowAdapter.add(list.get(j % 5));
        }
        HeaderItem header = new HeaderItem(i, MovieList.MOVIE_CATEGORY[i]);
        mRowsAdapter.add(new ListRow(header, listRowAdapter));
    }

    HeaderItem gridHeader = new HeaderItem(i, "PREFERENCES");

    GridItemPresenter mGridPresenter = new GridItemPresenter();
    ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter);
    gridRowAdapter.add(getResources().getString(R.string.grid_view));
    gridRowAdapter.add(getString(R.string.error_fragment));
    gridRowAdapter.add(getResources().getString(R.string.personal_settings));
    mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter));

    setAdapter(mRowsAdapter);

}

From source file:androidtvhackathon.mioandroidtv.MainFragment.java

private void loadRows() {
    List<Movie> list = MovieList.setupMovies();

    mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
    mCardPresenter = new CardPresenter();

    int i;/*from  w ww  .j  a v a2s.  c  o  m*/
    for (i = 0; i < NUM_ROWS; i++) {
        if (i != 0) {
            Collections.shuffle(list);
        }
        ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter);
        for (int j = 0; j < NUM_COLS; j++) {
            listRowAdapter.add(list.get(j % 5));
        }
        HeaderItem header = new HeaderItem(i, MovieList.MOVIE_CATEGORY[i], null);
        mRowsAdapter.add(new ListRow(header, listRowAdapter));
    }

    HeaderItem gridHeader = new HeaderItem(i, "PREFERENCES", null);

    GridItemPresenter mGridPresenter = new GridItemPresenter();
    ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter);
    gridRowAdapter.add(getResources().getString(R.string.grid_view));
    gridRowAdapter.add(getString(R.string.error_fragment));
    gridRowAdapter.add(getResources().getString(R.string.personal_settings));
    mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter));

    setAdapter(mRowsAdapter);

}

From source file:com.androidtvhackathon_feb2015.kush2.cahtelevision.MainFragment.java

private void loadRows() {
    List<Movie> list = MovieList.setupMovies();

    mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
    mCardPresenter = new CardPresenter();

    int i;/*  www.j  av a 2s  . c  o  m*/
    for (i = 0; i < NUM_ROWS; i++) {
        if (i != 0) {
            Collections.shuffle(list);
        }
        ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter);
        for (int j = 0; j < NUM_COLS; j++) {
            listRowAdapter.add(list.get(j % 5));
        }
        HeaderItem header = new HeaderItem(i, MovieList.MOVIE_CATEGORY[i], null);
        mRowsAdapter.add(new ListRow(header, listRowAdapter));
    }

    HeaderItem gridHeader = new HeaderItem(i, "Players", null);

    GridItemPresenter mGridPresenter = new GridItemPresenter();
    ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter);
    //gridRowAdapter.add(getResources().getString(R.string.grid_view));
    //gridRowAdapter.add(getString(R.string.error_fragment));
    gridRowAdapter.add(getResources().getString(R.string.personal_settings));
    mRowsAdapter.add(new ListRow(gridHeader, gridRowAdapter));

    setAdapter(mRowsAdapter);

}

From source file:com.zz.cluster4spring.support.invocation.ShuffleEndpointSelectionPolicy.java

/**
 * Selects endpoint for invocation from the given list of endpoints. This
 * implementation creates copy of given list, shuffle it and selects
 * firstendpoint from resulting list./* w  w  w.j  a  va 2s.  c  o m*/
 *
 * @param aEndpoints
 *            list of endpoints available for invocation of remote service
 * @return selected endpoints
 * @throws org.springframework.remoting.RemoteAccessException
 *             throw if some error occured during seleting endpoint for
 *             invocation
 * @see Collections#shuffle(java.util.List)
 */
public E selectServiceEndpoint(List<E> aEndpoints) throws RemoteAccessException {
    if (aEndpoints == null) {
        String message = "Unable to obtain service endpoint - list of endpoints is null";
        if (fLog.isErrorEnabled()) {
            fLog.error(message);
        }
        throw new RemoteAccessException(message);
    }

    // we create copy of originated list, shuffle it and select first item
    // from that list
    List<E> copy = new ArrayList<E>(aEndpoints);
    Collections.shuffle(copy);
    E result = copy.get(0);
    if (fLog.isTraceEnabled()) {
        SI serviceInfo = result.getServiceInfo();
        String message = format("EndPoint selected. Service URL: [{0}]", serviceInfo);
        fLog.trace(message);
    }
    return result;
}

From source file:com.graphaware.neo4j.webexpo.database.DataGenerator.java

/**
 * Find a number of random attendees.//from  w ww .j  a  v a  2s.c  om
 *
 * @param number of attendees to find.
 * @return the given number of random attendees.
 */
public List<String> findRandomAttendees(int number) {
    List<String> allAttendees = findAllAttendees();
    Collections.shuffle(allAttendees);
    return allAttendees.subList(0, number);
}

From source file:herddb.cluster.PreferLocalBookiePlacementPolicy.java

@Override
public ArrayList<BookieSocketAddress> newEnsemble(int ensembleSize, int quorumSize,
        Set<BookieSocketAddress> excludeBookies) throws BKException.BKNotEnoughBookiesException {

    ArrayList<BookieSocketAddress> newBookies = new ArrayList<>(ensembleSize);
    if (ensembleSize <= 0) {
        return newBookies;
    }//from   w  w  w.  jav  a 2s .  c  o m
    List<BookieSocketAddress> allBookies;
    synchronized (this) {
        allBookies = new ArrayList<>(knownBookies);
    }

    BookieSocketAddress localBookie = null;
    for (BookieSocketAddress bookie : allBookies) {
        if (excludeBookies.contains(bookie)) {
            continue;
        }
        if (isLocalBookie(bookie)) {
            localBookie = bookie;
            break;
        }
    }
    if (localBookie != null) {
        boolean ret = allBookies.remove(localBookie);
        if (!ret) {
            throw new RuntimeException("localBookie not found in list");
        }
        newBookies.add(localBookie);
        --ensembleSize;
        if (ensembleSize == 0) {
            return newBookies;
        }
    }

    Collections.shuffle(allBookies);
    for (BookieSocketAddress bookie : allBookies) {
        if (excludeBookies.contains(bookie)) {
            continue;
        }
        newBookies.add(bookie);
        --ensembleSize;
        if (ensembleSize == 0) {
            return newBookies;
        }
    }

    throw new BKException.BKNotEnoughBookiesException();
}

From source file:com.github.lukaszbudnik.gugis.GugisInterceptor.java

@Override
public Object invoke(MethodInvocation i) throws Throwable {
    if (log.isDebugEnabled()) {
        log.debug(/*from  www . j a va  2  s .  c o  m*/
                "Method " + i.getMethod() + " is called on " + i.getThis() + " with args " + i.getArguments());
    }

    Propagate propagate = i.getMethod().getAnnotation(Propagate.class);

    Class clazz = i.getMethod().getDeclaringClass().getInterfaces()[0];

    if (log.isDebugEnabled()) {
        log.debug("About to find bindings for " + clazz);
        log.debug("Propagation set to " + propagate.propagation());
        log.debug("Allow failure set to " + propagate.allowFailure());
    }

    List<Binding<Object>> bindings = injector.findBindingsByType(TypeLiteral.get(clazz));

    if (bindings.size() == 0) {
        log.error("No bindings found for " + clazz);
        throw new GugisException("No bindings found for " + clazz);
    }

    if (log.isDebugEnabled()) {
        log.debug("Found " + bindings.size() + " bindings for " + clazz);
    }

    Observable<Try<Object>> resultsObservable = null;
    switch (propagate.propagation()) {
    //            case FASTEST: {
    //                Observable<Binding<Object>> bindingsObservable = Observable.from(bindings);
    //                Observable<Try<Object>> executedObservable = executeBindings(propagate.allowFailure(), bindingsObservable, i.getMethod().getName(), i.getArguments());
    //                resultsObservable = executedObservable.debounce(5, TimeUnit.MILLISECONDS);
    //                break;
    //            }
    case PRIMARY: {
        resultsObservable = executeRxBindingsForRole(i, bindings, propagate.allowFailure(), Primary.class);
        break;
    }
    case SECONDARY: {
        resultsObservable = executeRxBindingsForRole(i, bindings, propagate.allowFailure(), Secondary.class);
        break;
    }
    case RANDOM: {
        ArrayList<Binding<Object>> modifiableBindings = new ArrayList<Binding<Object>>(bindings);
        Collections.shuffle(modifiableBindings);
        for (Binding<Object> binding : modifiableBindings) {
            Observable<Binding<Object>> bindingsObservable = Observable.just(binding);
            Observable<Try<Object>> executedObservable = executeBindings(propagate.allowFailure(),
                    bindingsObservable, i.getMethod().getName(), i.getArguments());

            Try<Object> tryObject = executedObservable.toBlocking().first();

            if (tryObject.isSuccess()) {
                resultsObservable = Observable.just(tryObject);
                break;
            }
        }
        break;
    }
    default: {
        // handles ALL
        Observable<Binding<Object>> bindingsObservable = Observable.from(bindings);
        resultsObservable = executeBindings(propagate.allowFailure(), bindingsObservable,
                i.getMethod().getName(), i.getArguments());
        break;
    }
    }

    List<Try<Object>> results = resultsObservable.toList().toBlocking().first();

    List<Try<Object>> successes = FluentIterable.from(results).filter(new Predicate<Try<Object>>() {
        @Override
        public boolean apply(Try<Object> input) {
            return input.isSuccess();
        }
    }).toList();

    if (successes.size() == 0) {
        String errorMessage = ErrorMessageBuilder
                .buildErrorMessageFromTries("No result for " + propagate.propagation() + " found for "
                        + clazz.getCanonicalName() + "." + i.getMethod().getName(), results);
        throw new GugisException(errorMessage);
    }

    // all implementations should be homogeneous and should return same value for same arguments
    Try<Object> tryObject = successes.get(0);

    if (log.isDebugEnabled()) {
        log.debug("Method " + i.getMethod() + " returns " + tryObject.get());
    }

    return tryObject.get();
}