Tabnine Logo
Collections.shuffle
Code IndexAdd Tabnine to your IDE (free)

How to use
shuffle
method
in
java.util.Collections

Best Java code snippets using java.util.Collections.shuffle (Showing top 20 results out of 10,854)

Refine searchRefine arrow

  • List.add
  • ArrayList.<init>
  • List.size
  • List.get
  • PrintStream.println
  • Arrays.asList
origin: square/picasso

SampleGridViewAdapter(Context context) {
 this.context = context;
 // Ensure we get a different ordering of images on each run.
 Collections.addAll(urls, Data.URLS);
 Collections.shuffle(urls);
 // Triple up the list.
 ArrayList<String> copy = new ArrayList<>(urls);
 urls.addAll(copy);
 urls.addAll(copy);
}
origin: apache/storm

@Override
public void prepare(WorkerTopologyContext context, GlobalStreamId stream, List<Integer> targetTasks) {
  choices = new ArrayList<List<Integer>>(targetTasks.size());
  for (Integer i : targetTasks) {
    choices.add(Arrays.asList(i));
  }
  current = new AtomicInteger(0);
  Collections.shuffle(choices, new Random());
}
origin: apache/kafka

private Collection<SelectionKey> determineHandlingOrder(Set<SelectionKey> selectionKeys) {
  //it is possible that the iteration order over selectionKeys is the same every invocation.
  //this may cause starvation of reads when memory is low. to address this we shuffle the keys if memory is low.
  if (!outOfMemory && memoryPool.availableMemory() < lowMemThreshold) {
    List<SelectionKey> shuffledKeys = new ArrayList<>(selectionKeys);
    Collections.shuffle(shuffledKeys);
    return shuffledKeys;
  } else {
    return selectionKeys;
  }
}
origin: stackoverflow.com

List<Integer> mutableList = new ArrayList<Integer>();
 mutableList.add(1);
 mutableList.add(2);
 mutableList.add(3);
 mutableList.add(4);
 mutableList.add(5);
 System.out.println(mutableList);
 Collections.shuffle(mutableList);
 System.out.println(mutableList);
 Collections.sort(mutableList);
 System.out.println(mutableList);
origin: alibaba/canal

private void initClusters(List<String> currentChilds) {
  if (currentChilds == null || currentChilds.isEmpty()) {
    currentAddress = new ArrayList<InetSocketAddress>();
  } else {
    List<InetSocketAddress> addresses = new ArrayList<InetSocketAddress>();
    for (String address : currentChilds) {
      String[] strs = StringUtils.split(address, ":");
      if (strs != null && strs.length == 2) {
        addresses.add(new InetSocketAddress(strs[0], Integer.valueOf(strs[1])));
      }
    }
    Collections.shuffle(addresses);
    currentAddress = addresses;// 直接切换引用
  }
}
origin: h2oai/h2o-3

ArrayList<Integer> ntreesList = new ArrayList<>(Arrays.asList(ntreesArr));
Collections.shuffle(ntreesList);
Integer[] ntreesSpace = new Integer[ntreesDim];
for (int i = 0; i < ntreesDim; i++) {
ArrayList<Integer> maxDepthList = new ArrayList<>(Arrays.asList(maxDepthArr));
Collections.shuffle(maxDepthList);
Integer[] maxDepthSpace = new Integer[maxDepthDim];
for (int i = 0; i < maxDepthDim; i++) {
ArrayList<Integer> mtriesList = new ArrayList<>(Arrays.asList(mtriesArr));
Collections.shuffle(mtriesList);
Integer[] mtriesSpace = new Integer[mtriesDim];
for (int i = 0; i < mtriesDim; i++) {
ArrayList<Double> sampleRateList = new ArrayList<>(Arrays.asList(sampleRateArr));
Collections.shuffle(sampleRateList);
Double[] sampleRateSpace = new Double[sampleRateDim];
for (int i = 0; i < sampleRateDim; i++) {
grid = gs.get();
System.out.println("Test seed: " + seed);
System.out.println("ntrees search space: " + Arrays.toString(ntreesSpace));
System.out.println("max_depth search space: " + Arrays.toString(maxDepthSpace));
System.out.println("mtries search space: " + Arrays.toString(mtriesSpace));
System.out.println("sample_rate search space: " + Arrays.toString(sampleRateSpace));
origin: apache/zookeeper

private InetSocketAddress resolve(InetSocketAddress address) {
  try {
    String curHostString = address.getHostString();
    List<InetAddress> resolvedAddresses = new ArrayList<>(Arrays.asList(this.resolver.getAllByName(curHostString)));
    if (resolvedAddresses.isEmpty()) {
      return address;
    }
    Collections.shuffle(resolvedAddresses);
    return new InetSocketAddress(resolvedAddresses.get(0), address.getPort());
  } catch (UnknownHostException e) {
    LOG.error("Unable to resolve address: {}", address.toString(), e);
    return address;
  }
}
origin: google/guava

private Element[] createQueries(Set<Element> elementsInSet, int numQueries) {
 List<Element> queryList = Lists.newArrayListWithCapacity(numQueries);
 int numGoodQueries = (int) (numQueries * hitRate + 0.5);
 // add good queries
 int size = elementsInSet.size();
 if (size > 0) {
  int minCopiesOfEachGoodQuery = numGoodQueries / size;
  int extras = numGoodQueries % size;
  for (int i = 0; i < minCopiesOfEachGoodQuery; i++) {
   queryList.addAll(elementsInSet);
  }
  List<Element> tmp = Lists.newArrayList(elementsInSet);
  Collections.shuffle(tmp, random);
  queryList.addAll(tmp.subList(0, extras));
 }
 // now add bad queries
 while (queryList.size() < numQueries) {
  Element candidate = newElement();
  if (!elementsInSet.contains(candidate)) {
   queryList.add(candidate);
  }
 }
 Collections.shuffle(queryList, random);
 return queryList.toArray(new Element[0]);
}
origin: xtuhcy/gecco

public static String getUserAgent(boolean isMobile) {
  if(isMobile) {
    if(mobileUserAgents == null || mobileUserAgents.size() == 0) {
      return DEFAULT_MOBILE_USER_AGENT;
    }
    Collections.shuffle(mobileUserAgents);
    return mobileUserAgents.get(0);
  } else {
    if(userAgents == null || userAgents.size() == 0) {
      return DEFAULT_USER_AGENT;
    }
    Collections.shuffle(userAgents);
    return userAgents.get(0);
  }
}
origin: voldemort/voldemort

public List<Node> routeHint(Node origin) {
  List<Node> prefList = Lists.newArrayListWithCapacity(nodes.size());
  int originZoneId = origin.getZoneId();
  for(Node node: nodes) {
    if(node.getId() != origin.getId()) {
      if(enableZoneRouting && zones.size() > 1) {
        if(originZoneId == clientZoneId) {
          if(node.getZoneId() != clientZoneId)
            continue;
        } else {
          if(node.getZoneId() == originZoneId)
            continue;
        }
      }
      prefList.add(node);
    }
  }
  Collections.shuffle(prefList);
  return prefList;
}
origin: stackoverflow.com

 import java.util.ArrayList;
import java.util.Collections;

public class UniqueRandomNumbers {

  public static void main(String[] args) {
    ArrayList<Integer> list = new ArrayList<Integer>();
    for (int i=1; i<11; i++) {
      list.add(new Integer(i));
    }
    Collections.shuffle(list);
    for (int i=0; i<3; i++) {
      System.out.println(list.get(i));
    }
  }
}
origin: stanfordnlp/CoreNLP

private void trainPolicy(List<List<Pair<CandidateAction, CandidateAction>>> examples) {
 List<Pair<CandidateAction, CandidateAction>> flattenedExamples = new ArrayList<>();
 examples.stream().forEach(flattenedExamples::addAll);
 for (int epoch = 0; epoch < NUM_EPOCHS; epoch++) {
  Collections.shuffle(flattenedExamples, random);
  flattenedExamples.forEach(classifier::learn);
 }
 double totalCost = flattenedExamples.stream()
   .mapToDouble(e -> classifier.bestAction(e).cost).sum();
 Redwood.log("scoref.train",
   String.format("Training cost: %.4f", 100 * totalCost / flattenedExamples.size()));
}
origin: oblac/jodd

private void assertListOrder(Comparator<String> c, String[] strings) {
  int loop = 100;
  while (loop-- > 0) {
    List<String> list = Arrays.asList(strings.clone());
    Collections.shuffle(list);
    list.sort(c);
    for (int i = 0, listSize = list.size(); i < listSize; i++) {
      String s = list.get(i);
      assertEquals(strings[i], s);
    }
  }
}
origin: spring-projects/spring-framework

@Test
public void compareToWithImpicitVsExplicitHttpMethodDeclaration() {
  RequestMappingInfo noMethods = paths().build();
  RequestMappingInfo oneMethod = paths().methods(GET).build();
  RequestMappingInfo oneMethodOneParam = paths().methods(GET).params("foo").build();
  Comparator<RequestMappingInfo> comparator =
      (info, otherInfo) -> info.compareTo(otherInfo, new MockHttpServletRequest());
  List<RequestMappingInfo> list = asList(noMethods, oneMethod, oneMethodOneParam);
  Collections.shuffle(list);
  Collections.sort(list, comparator);
  assertEquals(oneMethodOneParam, list.get(0));
  assertEquals(oneMethod, list.get(1));
  assertEquals(noMethods, list.get(2));
}
origin: stackoverflow.com

 public static void main(String[] args) {
  Integer[] arr = new Integer[1000];
  for (int i = 0; i < arr.length; i++) {
    arr[i] = i;
  }
  Collections.shuffle(Arrays.asList(arr));
  System.out.println(Arrays.toString(arr));

}
origin: apache/hbase

/**
 * Refresh the list of sinks.
 */
public synchronized void chooseSinks() {
 List<ServerName> slaveAddresses = endpoint.getRegionServers();
 Collections.shuffle(slaveAddresses, random);
 int numSinks = (int) Math.ceil(slaveAddresses.size() * ratio);
 sinks = slaveAddresses.subList(0, numSinks);
 lastUpdateToPeers = System.currentTimeMillis();
 badReportCounts.clear();
}
origin: neo4j/neo4j

  @Override
  public File[] listFiles( File directory )
  {
    List<File> files = asList( super.listFiles( directory ) );
    Collections.shuffle( files );
    return files.toArray( new File[files.size()] );
  }
} )
origin: google/guava

public void testCombineUnordered_randomHashCodes() {
 Random random = new Random(RANDOM_SEED);
 List<HashCode> hashCodes = Lists.newArrayList();
 for (int i = 0; i < 10; i++) {
  hashCodes.add(HashCode.fromLong(random.nextLong()));
 }
 HashCode hashCode1 = Hashing.combineUnordered(hashCodes);
 Collections.shuffle(hashCodes);
 HashCode hashCode2 = Hashing.combineUnordered(hashCodes);
 assertEquals(hashCode1, hashCode2);
}
origin: springside/springside4

/**
 * 从输入list中随机返回一个对象.
 */
public static <T> T randomOne(List<T> list) {
  Collections.shuffle(list);
  return list.get(0);
}
origin: stackoverflow.com

 List<Integer> integers =
  IntStream.range(1, 10)                      // <-- creates a stream of ints
    .boxed()                                // <-- converts them to Integers
    .collect(Collectors.toList());          // <-- collects the values to a list

Collections.shuffle(integers);

System.out.println(integers);
java.utilCollectionsshuffle

Javadoc

Moves every element of the list to a random new position in the list.

Popular methods of Collections

  • emptyList
    Returns the empty list (immutable). This list is serializable.This example illustrates the type-safe
  • sort
  • singletonList
    Returns an immutable list containing only the specified object. The returned list is serializable.
  • unmodifiableList
    Returns an unmodifiable view of the specified list. This method allows modules to provide users with
  • emptyMap
    Returns the empty map (immutable). This map is serializable.This example illustrates the type-safe w
  • emptySet
    Returns the empty set (immutable). This set is serializable. Unlike the like-named field, this metho
  • unmodifiableMap
    Returns an unmodifiable view of the specified map. This method allows modules to provide users with
  • singleton
    Returns an immutable set containing only the specified object. The returned set is serializable.
  • unmodifiableSet
    Returns an unmodifiable view of the specified set. This method allows modules to provide users with
  • singletonMap
    Returns an immutable map, mapping only the specified key to the specified value. The returned map is
  • addAll
    Adds all of the specified elements to the specified collection. Elements to be added may be specifie
  • reverse
    Reverses the order of the elements in the specified list. This method runs in linear time.
  • addAll,
  • reverse,
  • unmodifiableCollection,
  • enumeration,
  • list,
  • synchronizedMap,
  • synchronizedList,
  • reverseOrder,
  • emptyIterator

Popular in Java

  • Making http requests using okhttp
  • scheduleAtFixedRate (ScheduledExecutorService)
  • onCreateOptionsMenu (Activity)
  • getExternalFilesDir (Context)
  • EOFException (java.io)
    Thrown when a program encounters the end of a file or stream during an input operation.
  • FileOutputStream (java.io)
    An output stream that writes bytes to a file. If the output file exists, it can be replaced or appen
  • Runnable (java.lang)
    Represents a command that can be executed. Often used to run code in a different Thread.
  • UnknownHostException (java.net)
    Thrown when a hostname can not be resolved.
  • BitSet (java.util)
    The BitSet class implements abit array [http://en.wikipedia.org/wiki/Bit_array]. Each element is eit
  • CountDownLatch (java.util.concurrent)
    A synchronization aid that allows one or more threads to wait until a set of operations being perfor
  • Top plugins for Android Studio
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now