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:NaturalOrderComparator.java

public static void main(String[] args) {
    String[] strings = new String[] { "1-2", "1-02", "1-20", "10-20", "fred", "jane", "pic01", "pic2", "pic02",
            "pic02a", "pic3", "pic4", "pic 4 else", "pic 5", "pic05", "pic 5", "pic 5 something", "pic 6",
            "pic   7", "pic100", "pic100a", "pic120", "pic121", "pic02000", "tom", "x2-g8", "x2-y7", "x2-y08",
            "x8-y8" };

    List orig = Arrays.asList(strings);

    System.out.println("Original: " + orig);

    List scrambled = Arrays.asList(strings);
    Collections.shuffle(scrambled);

    System.out.println("Scrambled: " + scrambled);

    Collections.sort(scrambled, new NaturalOrderComparator());

    System.out.println("Sorted: " + scrambled);
}

From source file:Main.java

public static <V> List<V> shuffleAndSubList(List<V> list, int subSize) {
    if (list == null || list.size() == 0) {
        return null;
    }/* ww  w . j a  va 2s . c  o  m*/
    Collections.shuffle(list);
    list = list.size() > subSize ? list.subList(0, subSize) : list;
    return list;
}

From source file:Main.java

public static String random(String src) {
    String[] srcList = src.split("");
    List<String> list = Arrays.asList(srcList);
    Collections.shuffle(list);
    StringBuilder result = new StringBuilder();
    for (String i : list) {
        result.append(i);/*from w  ww. j  av a  2 s  .c  o m*/
    }
    return result.toString();
}

From source file:Main.java

public static void shuffleArray(int[] array) {
    List<Integer> list = new ArrayList<>();
    for (int i : array) {
        list.add(i);/*  www.  j  a  v a 2 s. co  m*/
    }

    Collections.shuffle(list);

    for (int i = 0; i < list.size(); i++) {
        array[i] = list.get(i);
    }
}

From source file:Main.java

public static String doDraw(String cardName[], int length) {
    List<String> cardList = Arrays.asList(cardName);
    Collections.shuffle(cardList);
    return cardList.toString();
}

From source file:Main.java

public static <K, V> List<V> selectRandom(Map<K, V> map, int size) {
    if (isNull(map)) {
        return null;
    }/*from  ww w  .j  a  va  2  s .c o m*/
    List<V> values = valueToList(map);
    if (values.size() <= size) {
        return new ArrayList<V>(values);
    }
    Collections.shuffle(values);
    return values.subList(0, size);
}

From source file:Main.java

public static void split(String[] items, ArrayList<String> res, int number) {
    // split items to res1 and res2, where res2 has number items
    res.clear();//from   w w  w . j  a  v a2s .c  o  m
    String res1 = "";
    String res2 = "";
    ArrayList<String> newList = new ArrayList<String>();
    for (int i = 0; i < items.length; i++) {
        newList.add(items[i]);
    }
    Collections.shuffle(newList);
    for (int i = 0; i < newList.size(); i++) {
        if (i < number) {
            res1 += newList.get(i) + "\t";
        } else {
            res2 += newList.get(i) + "\t";
        }
    }
    res.add(res1);
    res.add(res2);
}

From source file:Main.java

public static <T> ArrayList<T> shuffle(ArrayList<T> population, int sample) {
    ArrayList<T> newList = new ArrayList<T>();
    ArrayList<T> ret = new ArrayList<T>();
    newList.addAll(population);//from  w  ww . j  a va  2  s.c  o m

    Collections.shuffle(newList);
    ret.addAll(newList);
    for (int i = sample; i < ret.size(); i++) {
        ret.remove(i);
        i--;
    }
    newList.clear();
    return ret;
}

From source file:com.shirokumacafe.archetype.common.utilities.RandomData.java

/**
 * list?.
 */
public static <T> T randomOne(List<T> list) {
    Collections.shuffle(list);
    return list.get(0);
}

From source file:com.yahoo.pulsar.testclient.PerformanceProducer.java

public static void main(String[] args) throws Exception {
    final Arguments arguments = new Arguments();
    JCommander jc = new JCommander(arguments);
    jc.setProgramName("pulsar-perf-producer");

    try {/*from ww w. j ava 2  s. c om*/
        jc.parse(args);
    } catch (ParameterException e) {
        System.out.println(e.getMessage());
        jc.usage();
        System.exit(-1);
    }

    if (arguments.help) {
        jc.usage();
        System.exit(-1);
    }

    if (arguments.destinations.size() != 1) {
        System.out.println("Only one topic name is allowed");
        jc.usage();
        System.exit(-1);
    }

    if (arguments.confFile != null) {
        Properties prop = new Properties(System.getProperties());
        prop.load(new FileInputStream(arguments.confFile));

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("brokerServiceUrl");
        }

        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("webServiceUrl");
        }

        // fallback to previous-version serviceUrl property to maintain backward-compatibility
        if (arguments.serviceURL == null) {
            arguments.serviceURL = prop.getProperty("serviceUrl", "http://localhost:8080/");
        }

        if (arguments.authPluginClassName == null) {
            arguments.authPluginClassName = prop.getProperty("authPlugin", null);
        }

        if (arguments.authParams == null) {
            arguments.authParams = prop.getProperty("authParams", null);
        }
    }

    arguments.testTime = TimeUnit.SECONDS.toMillis(arguments.testTime);

    // Dump config variables
    ObjectMapper m = new ObjectMapper();
    ObjectWriter w = m.writerWithDefaultPrettyPrinter();
    log.info("Starting Pulsar perf producer with config: {}", w.writeValueAsString(arguments));

    // Read payload data from file if needed
    byte payloadData[];
    if (arguments.payloadFilename != null) {
        payloadData = Files.readAllBytes(Paths.get(arguments.payloadFilename));
    } else {
        payloadData = new byte[arguments.msgSize];
    }

    // Now processing command line arguments
    String prefixTopicName = arguments.destinations.get(0);
    List<Future<Producer>> futures = Lists.newArrayList();

    EventLoopGroup eventLoopGroup;
    if (SystemUtils.IS_OS_LINUX) {
        eventLoopGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-producer"));
    } else {
        eventLoopGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors(),
                new DefaultThreadFactory("pulsar-perf-producer"));
    }

    ClientConfiguration clientConf = new ClientConfiguration();
    clientConf.setConnectionsPerBroker(arguments.maxConnections);
    clientConf.setStatsInterval(arguments.statsIntervalSeconds, TimeUnit.SECONDS);
    if (isNotBlank(arguments.authPluginClassName)) {
        clientConf.setAuthentication(arguments.authPluginClassName, arguments.authParams);
    }

    PulsarClient client = new PulsarClientImpl(arguments.serviceURL, clientConf, eventLoopGroup);

    ProducerConfiguration producerConf = new ProducerConfiguration();
    producerConf.setSendTimeout(0, TimeUnit.SECONDS);
    producerConf.setCompressionType(arguments.compression);
    // enable round robin message routing if it is a partitioned topic
    producerConf.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
    if (arguments.batchTime > 0) {
        producerConf.setBatchingMaxPublishDelay(arguments.batchTime, TimeUnit.MILLISECONDS);
        producerConf.setBatchingEnabled(true);
        producerConf.setMaxPendingMessages(arguments.msgRate);
    }

    for (int i = 0; i < arguments.numTopics; i++) {
        String topic = (arguments.numTopics == 1) ? prefixTopicName
                : String.format("%s-%d", prefixTopicName, i);
        log.info("Adding {} publishers on destination {}", arguments.numProducers, topic);

        for (int j = 0; j < arguments.numProducers; j++) {
            futures.add(client.createProducerAsync(topic, producerConf));
        }
    }

    final List<Producer> producers = Lists.newArrayListWithCapacity(futures.size());
    for (Future<Producer> future : futures) {
        producers.add(future.get());
    }

    log.info("Created {} producers", producers.size());

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run() {
            printAggregatedStats();
        }
    });

    Collections.shuffle(producers);
    AtomicBoolean isDone = new AtomicBoolean();

    executor.submit(() -> {
        try {
            RateLimiter rateLimiter = RateLimiter.create(arguments.msgRate);

            long startTime = System.currentTimeMillis();

            // Send messages on all topics/producers
            long totalSent = 0;
            while (true) {
                for (Producer producer : producers) {
                    if (arguments.testTime > 0) {
                        if (System.currentTimeMillis() - startTime > arguments.testTime) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }

                    if (arguments.numMessages > 0) {
                        if (totalSent++ >= arguments.numMessages) {
                            log.info("------------------- DONE -----------------------");
                            printAggregatedStats();
                            isDone.set(true);
                            Thread.sleep(5000);
                            System.exit(0);
                        }
                    }
                    rateLimiter.acquire();

                    final long sendTime = System.nanoTime();

                    producer.sendAsync(payloadData).thenRun(() -> {
                        messagesSent.increment();
                        bytesSent.add(payloadData.length);

                        long latencyMicros = NANOSECONDS.toMicros(System.nanoTime() - sendTime);
                        recorder.recordValue(latencyMicros);
                        cumulativeRecorder.recordValue(latencyMicros);
                    }).exceptionally(ex -> {
                        log.warn("Write error on message", ex);
                        System.exit(-1);
                        return null;
                    });
                }
            }
        } catch (Throwable t) {
            log.error("Got error", t);
        }
    });

    // Print report stats
    long oldTime = System.nanoTime();

    Histogram reportHistogram = null;

    String statsFileName = "perf-producer-" + System.currentTimeMillis() + ".hgrm";
    log.info("Dumping latency stats to {}", statsFileName);

    PrintStream histogramLog = new PrintStream(new FileOutputStream(statsFileName), false);
    HistogramLogWriter histogramLogWriter = new HistogramLogWriter(histogramLog);

    // Some log header bits
    histogramLogWriter.outputLogFormatVersion();
    histogramLogWriter.outputLegend();

    while (true) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            break;
        }

        if (isDone.get()) {
            break;
        }

        long now = System.nanoTime();
        double elapsed = (now - oldTime) / 1e9;

        double rate = messagesSent.sumThenReset() / elapsed;
        double throughput = bytesSent.sumThenReset() / elapsed / 1024 / 1024 * 8;

        reportHistogram = recorder.getIntervalHistogram(reportHistogram);

        log.info(
                "Throughput produced: {}  msg/s --- {} Mbit/s --- Latency: mean: {} ms - med: {} - 95pct: {} - 99pct: {} - 99.9pct: {} - 99.99pct: {} - Max: {}",
                throughputFormat.format(rate), throughputFormat.format(throughput),
                dec.format(reportHistogram.getMean() / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(50) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(95) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.9) / 1000.0),
                dec.format(reportHistogram.getValueAtPercentile(99.99) / 1000.0),
                dec.format(reportHistogram.getMaxValue() / 1000.0));

        histogramLogWriter.outputIntervalHistogram(reportHistogram);
        reportHistogram.reset();

        oldTime = now;
    }

    client.close();
}