Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/* *********************************************************************** *
 * project: org.matsim.*
 * CollectionUtils.java
 *                                                                         *
 * *********************************************************************** *
 *                                                                         *
 * copyright       : (C) 2013 by the members listed in the COPYING,        *
 *                   LICENSE and WARRANTY file.                            *
 * email           : info at matsim dot org                                *
 *                                                                         *
 * *********************************************************************** *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *   See also COPYING, LICENSE and WARRANTY file                           *
 *                                                                         *
 * *********************************************************************** */

import java.util.Iterator;

import java.util.Map;
import java.util.Random;

public class Main {
    /**
     * makes sense only if iteration order deterministic!
     */
    public static <K, V> Map.Entry<K, V> getRandomElement(final Random random, final Map<K, V> map) {
        return getRandomElement(false, random, map);
    }

    /**
     * makes sense only if iteration order deterministic!
     */
    private static <K, V> Map.Entry<K, V> getRandomElement(final boolean remove, final Random random,
            final Map<K, V> map) {
        if (map.isEmpty())
            throw new IllegalArgumentException("map is empty!");
        final int index = random.nextInt(map.size());

        final Iterator<Map.Entry<K, V>> it = map.entrySet().iterator();
        int i = 0;

        while (i++ < index)
            it.next();

        final Map.Entry<K, V> elem = it.next();
        if (remove)
            it.remove();
        return elem;
    }
}