Monday 25 July 2022

How to get a random element from Set?

Problem statement

Get a random element from the set.

 

Solution

Step 1: Get a random number ‘n’ between 1 and set.size.

Integer randPosition = new SecureRandom().nextInt(set.size());

 

Step 2: Iterate over the set and return the number at nth iteration.


 

Find the below working application.

 

SetUtil.java

package com.sample.app.reflections;

import java.security.SecureRandom;
import java.util.Iterator;
import java.util.Set;

public class SetUtil {

    public static <T> T randomElement(Set<T> set) {

        if (set == null || set.isEmpty()) {
            return null;
        }

        Integer randPosition = new SecureRandom().nextInt(set.size());

        Iterator<T> iter = set.iterator();

        int counter = 0;
        while (iter.hasNext()) {

            if (counter == randPosition) {
                return iter.next();
            }
            iter.next();
            counter++;

        }

        return null;
    }

}

 

App.java

package com.sample.app;

import java.util.HashSet;
import java.util.Set;

import com.sample.app.reflections.SetUtil;

public class App {
    public static void main(String[] args) {
        Set<Integer> primes = new HashSet<>();

        primes.add(2);
        primes.add(3);
        primes.add(5);
        primes.add(7);
        primes.add(11);
        primes.add(13);
        primes.add(17);
        primes.add(19);
        primes.add(23);
        primes.add(29);

        for (int i = 0; i < 10; i++) {
            System.out.println(SetUtil.randomElement(primes));
        }

    }
}

  Sample Output

 

17
11
7
5
17
17
23
29
7
7

 

 

 

You may like

Interview Questions

What is the behaviour of static final method in Java?

How to check two double values for equality?

Why to do explicit type casting from double to float conversion?

When is a class or interface is initialized or loaded in Java?

How to check two float values equality?

How to check whether a class is loaded or not in Java?

No comments:

Post a Comment