Friday 6 March 2020

How to pick random element from Set?

Approach 1: Generate a random number between 0 and size of set and return the element by iterating random number of times.
public static <T> T getRandomItem_approach1(Set<T> set) {
 if (set == null || set.isEmpty()) {
  return null;
 }

 int number = getRandomNumber(set.size());

 int i = 0;

 T result = null;

 for (T obj : set) {
  if (i == number) {
   result = obj;
   break;
  }
  i++;
 }

 return result;

}

Approach 2: Using streams.
public static <T> T getRandomItem_approach2(Set<T> set) {
 if (set == null || set.isEmpty()) {
  return null;
 }

 int randomNumber = getRandomNumber(set.size());

 return set.stream().skip(randomNumber).findFirst().orElse(null);
}

App.java
package com.sample.app;

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

public class App {

 private static int getRandomNumber(int size) {
  return new Random().nextInt(size);
 }

 public static <T> T getRandomItem_approach1(Set<T> set) {
  if (set == null || set.isEmpty()) {
   return null;
  }

  int number = getRandomNumber(set.size());

  int i = 0;

  T result = null;

  for (T obj : set) {
   if (i == number) {
    result = obj;
    break;
   }
   i++;
  }

  return result;

 }

 public static <T> T getRandomItem_approach2(Set<T> set) {
  if (set == null || set.isEmpty()) {
   return null;
  }

  int randomNumber = getRandomNumber(set.size());

  return set.stream().skip(randomNumber).findFirst().orElse(null);
 }

 public static void main(String[] args) {
  Set<String> countries = new HashSet<>();

  countries.add("India");
  countries.add("Bangladesh");
  countries.add("Nepal");
  countries.add("Srilanka");
  countries.add("Australia");

  String item1 = getRandomItem_approach1(countries);
  String item2 = getRandomItem_approach2(countries);

  System.out.println(item1);
  System.out.println(item2);

 }

}


You may like

No comments:

Post a Comment