Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Inside the Random Generator

DZone's Guide to

Inside the Random Generator

If you feel like you need a bit of randomness in your life, this look at the logic of randomization in Java could be what you need.

· Java Zone
Free Resource

Microservices! They are everywhere, or at least, the term is. When should you use a microservice architecture? What factors should be considered when making that decision? Do the benefits outweigh the costs? Why is everyone so excited about them, anyway?  Brought to you in partnership with IBM.

In the first part of my series on RandomGenerator, I provided the background of my personal project to create a shared library or component to be used for a side project I was working on. I also provided a couple use case examples that can be handled by the RandomGenerator.

This article is going to focus on the code handling the randomization itself.

Simple Randomization

The simplest implementation of RandomGenerator uses the following method:

public List<T> randomize(List<T> tList) {}


An example of this usage was provided in my last article, which basically randomized a list of vacation destinations. Inside the program logic, the randomize() method calls a preProcessing() method, which in turn calls the handleRandomization() method, to actually perform the randomization of the list.

Since the preProcessing() method is handling some of the additional functionality added in other overloaded methods, I will skip this section of the code for now and focus on the heart of the handleRandomization() method.

Below, is a simplified version of the handleRandomization() method, excluding some of the extra functionality that exists with the overloaded randomize() methods:

private void handleRandomization(List<RandomListItem> randomListItems, List<RandomListItem> returnList) {
    while (randomListItems.size() > 0) {
        int listSize = randomListItems.size();
        int winner = 0;

        if (listSize != 1) {
            Random random = new Random();
            winner = random.nextInt(listSize);
        }

        RandomListItem randomListItem = randomListItems.get(winner);
        returnList.add(randomListItem);

        // Remove winning item from list
    }
}


There are two Lists passed into the handleRandomization() method, both of type RandomListItem, which is a private inner-class defined as shown below:

@Data
private class RandomListItem {
    public RandomListItem(String originalToString, T thisT) {
        this.originalToString = originalToString;
        this.thisT = thisT;
    }

    private String originalToString;
    private T thisT;
}


Please note: I am using the lombok @Data annotation to save having to specify getters/setters/etc.

This inner-class is used for the rating functionality and can be ignored at this point.

Getting back to the handleRandomization() method, a while loop continues as long as there are values in the source List (randomListItems) to process. Inside that loop, the following tasks take place:

  • Set the listSize integer to the current size of the randomListItems list.

  • Set the winner integer to zero.

  • If the list size is not equal to one, pick a random int up to the size of the listSize integer and set it to the value of the winner integer
    (if the list size is equal to one, that is the winner).

  • Set a temporary RandomListItem to the value of the winner.

  • Add the RandomListItem to the returnList object, which should be in a different order.

  • Remove winning item from list (which will be discussed in my next article).

The returnList object is returned to the calling method, providing results in a different order.

Looking Ahead

I realize the java.util.Collections object includes a shuffle() method, which can handle the use case listed above. However, the functionality I require for my personal project (which will be explained in my next article), does not exist within the shuffle() method.

In my next article, I will focus on the other options available with RandomGenerator:

  • Limiting the results of the randomized list.

  • Adding a weight value to list items being randomized.

  • The RandomGenerator command-line interface (CLI).

Have a really great day!

Discover how the Watson team is further developing SDKs in Java, Node.js, Python, iOS, and Android to access these services and make programming easy. Brought to you in partnership with IBM.

Topics:
java ,lists ,randomness ,open source ,tutorial

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}