current position:Home>How does Java randomly get elements from a list
How does Java randomly get elements from a list
2022-04-29 04:34:46【51CTO】
summary
From a List Getting an element at random is about List A basic operation of , But this operation is not very obvious .
This page mainly shows you how to effectively start from List Get a random element and some methods you can use .
Select a random element
In order to List Get an element at random , You can randomly choose from List Get the subscript of an index in .
Then you can use this random subscript method List.get() To get elements at random .
The point of using this method is , Randomly generated subscripts should not exceed List’s Size , Otherwise, you will encounter overflow exceptions .
Single random element
To get a random subscript , You can use Random.nextInt(int bound) Method .
Look at the following code :
public void givenList_shouldReturnARandomElement() {
List<Integer> givenList = Arrays.asList(1, 2, 3);
Random rand = new Random();
int randomElement = givenList.get(rand.nextInt(givenList.size()));
}
- 1.
- 2.
- 3.
- 4.
- 5.
If you don't want to use it Random class , You can use Math.random() This static method , Then multiply the generated random number by List Size . (Math.random()) Will generate Double Random variable of .
The interval of this random variable is 0 and 1 Between , This variable contains 0, But it doesn't include 1.
After completing the above conversion , Don't forget to convert the obtained subscript to int type .
Select random subscripts in a multithreaded environment
In a multithreaded environment , How to use a single Random Class instance , This will cause every thread in this instance to access the same result .
We can use ThreadLocalRandom Class to create a new instance for each thread .
For example, the following code can ensure that the same random subscripts do not appear in multiple threads .
int randomElementIndex
= ThreadLocalRandom.current().nextInt(listSize) % givenList.size();
- 1.
- 2.
You can repeatedly select elements
occasionally , You may want to start from List Select some elements in , But these selected elements can be repeated .
The operation required is also very simple , Choose as many as you need , Just use a loop to do it .
Like the following code , Direct use cycle .
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsRepeat() {
Random rand = new Random();
List<String> givenList = Arrays.asList("one", "two", "three", "four");
int numberOfElements = 2;
for (int i = 0; i < numberOfElements; i++) {
int randomIndex = rand.nextInt(givenList.size());
String randomElement = givenList.get(randomIndex);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
Select non repeating elements
If you want the elements you choose not to repeat , You can change the selected elements from List Remove .
It should be noted that we are worried about the overflow of subscripts .
Like yours List The length is 10, But you want from here List Choose from 11 A non repeating element , There is no way to do this .
Usually throw an exception .
public void givenList_whenNumberElementsChosen_shouldReturnRandomElementsNoRepeat() {
Random rand = new Random();
List<String> givenList = Lists.newArrayList("one", "two", "three", "four");
int numberOfElements = 2;
for (int i = 0; i < numberOfElements; i++) {
int randomIndex = rand.nextInt(givenList.size());
String randomElement = givenList.get(randomIndex);
givenList.remove(randomIndex);
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
Choose a random sequence
The main purpose of this method is to give List Make a mess of , And get the same random sequence .
Of course, you can also use loops to do , If you use Collections Tools can better help you achieve this goal :
public void givenList_whenSeriesLengthChosen_shouldReturnRandomSeries() {
List<Integer> givenList = Lists.newArrayList(1, 2, 3, 4, 5, 6);
Collections.shuffle(givenList);
int randomSeriesLength = 3;
List<Integer> randomSeries = givenList.subList(0, randomSeriesLength);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
Conclusion
In this page , We are right. List The random output of elements in .
Through the above , Can better help you understand about List Random output in .
copyright notice
author[51CTO],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2022/04/202204290434413917.html
The sidebar is recommended
- Units that can be used by the rotate method of transform in CSS
- Why CSS3 sticky doesn't work?
- [bug resolution] webpack error: module not found Did you mean xxx
- Vue insert iframe
- About database data response to HTML page, Chinese appears? Solution to garbled code (multiple question marks)
- Ask a question about CSS selector
- When Vue jumps the route, the timer cannot be cleared in time
- Document is not defined
- Vuepress packaging deployment stepping on the road of the pit
- Vue quill editor stepping on pit record -- the echo style of rich text content is wrong
guess what you like
The multi selection box of table in element is combined with paging to echo the bug step hole
Vue project optimizes the loading speed of the first screen
Use / deep / to report an error CSS (CSS selected expected)
Nginx configuration
Vue cli reverse proxy
Vuex persistedstate plug-in - vuex persistent storage
Automatic import of less
Understanding and summary of CSS
vue2. Implementation of X data response
JavaScript content understanding
Random recommended
- Props in react
- JavaScript stack“
- Bootstrap blazor table component (III) intelligent generation
- Based on centos7 + nginx + Daphne + uwsgi + django3 2 + supervisor + mysql8 single architecture server production environment deployment (I)
- Differences between vue2 and vue3 named slots
- Vue3: Axios cross domain request problem
- The difference between vue2 and vue3: keep alive
- Configure nginx and SSL certificate for Django project under Windows Environment
- Ant Design Vue: a-table custom column
- Using jQuery in Vue
- Vue dynamic loading picture problem
- Icons using Alibaba vector icon library in Vue
- Java Android mobile phone automatic basic learning element positioning
- Rancher configuring HTTPS domain name to access graphic tutorial
- Building a blog with GitHub pages + hexo (7) how to delete a published article successfully solved: delete it at the same time deploy_ Git folder
- Eight blog views / hexubs
- Build a blog with GitHub pages + hexo (9) set the next theme of hexo blog, and only part of the home page is displayed (not the full text)
- Building a blog with GitHub pages + hexo (10) the next theme of hexo blog mathjax mathematical formula rendering problem
- Hexo/Github. IO configure Tencent cloud CDN
- Rich text editor: ckeditor (using ckeditor4 Vue)
- The get request of nginx agent only returns part of the data. The problem is solved
- JavaScript traverses the irregularly nested multi-layer objects, returns the map with "index", and realizes the rapid positioning of sub attributes
- HTTP keep alive details
- [technical update] http / 3 quic Foundation
- Vue to react ----- can the constructor be omitted when using ES6?
- Use of nested HTML
- Vue to react to realize slot function
- When to use react PureComponent
- Details of Vue to react useeffect
- React 16.6 memo()
- Deep understanding of children https://segmentfault.com/a/1190000011527160
- This paper solves the cross domain problem Vue + springboot caused by the separation of front and back ends
- The difference between shallow copy and deep copy is to use native JavaScript to realize deep copy
- Definition of Vue slot
- Sorting algorithm in JavaScript
- JavaScript implements search algorithm, sequential search and binary search
- leetcode20. Valid parentheses, implemented using JavaScript
- 496 next element larger JavaScript implementation leetcode
- Source code analysis, Vue What happens when using (), take initializing vuex as an example
- Vue bidirectional binding principle