How to pick a random value from a map in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.util.List;
import java.util.Map;

public class RandomPicker {
    // Function to get a random value from a map
    public static String getRandomValue(Map<Integer, String> inputMap) {
        List<String> values = new ArrayList<>(inputMap.values());
        
        Random random = new Random();
        int index = random.nextInt(values.size());
        
        return values.get(index);
    }

    public static void main(String[] args) {
        // Initialize the map
        Map<Integer, String> myMap = new HashMap<>();
        myMap.put(1, "C++");
        myMap.put(2, "C");
        myMap.put(3, "Java");
        myMap.put(4, "C#");
        myMap.put(5, "Rust");
        myMap.put(6, "Python");

        String randomValue = getRandomValue(myMap);

        System.out.println("Random value: " + randomValue);
    }
}


 
/*
run:

Random value: Rust
 
*/

 



answered Jul 16, 2025 by avibootz

Related questions

3 answers 143 views
2 answers 95 views
2 answers 180 views
2 answers 147 views
2 answers 165 views
...