本文整理了Java中java.util.Collections.shuffle()
方法的一些代码示例,展示了Collections.shuffle()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Collections.shuffle()
方法的具体详情如下:
包路径:java.util.Collections
类名称:Collections
方法名:shuffle
[英]Moves every element of the list to a random new position in the list.
[中]将列表中的每个元素随机移动到列表中的新位置。
代码示例来源: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);
内容来源于网络,如有侵权,请联系作者删除!