Java list random fetch record

Source: Internet
Author: User

Recently, we need to develop a random advertisement function. In the previous blog, we talked about the Oracle method.

In this article, we will share how to randomly fetch numbers in the Java list:

In fact, there is no method to randomly retrieve records in the list, but there is a shuffle method in collections to achieve the "shuffling" effect. The so-called "shuffling" means to disrupt the elements in the list and re-sort them. The list after the list is rearranged and the number of records to be sent from the first place is equivalent to the random number acquisition. For details, see the code.

Import Java. util. arraylist; <br/> Import Java. util. collections; <br/> Import Java. util. list; <br/> public class TTL {<br/> Public static void main (string [] Str) {<br/> List <integer> List = new arraylist <integer> (); <br/> for (INT I = 0; I <5; I ++) {<br/> list. add (I); <br/>}< br/> system. out. println ("orginal list:"); <br/> for (integer S: List) {<br/> system. out. print (s); <br/>}< br/> system. out. println (); </P> <p> collections. shuffle (list); <br/> system. out. println ("after shuffle list:"); <br/> for (integer S: List) {<br/> system. out. print (s); <br/>}< br/> 

Output result:

 

Orginal list:

01234

After shuffle list:

32041

 

 

The shuffle principle is to use the SWAp in the collection to implement random transposition of each element in the list. This means that this random method is not suitable for the random of many records in the list.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.