Languages
[Edit]
EN

Java - get random key value element from hash map

5 points
Created by:
Marcin
2462

1. Generate random key value from hash map

import java.util.*;

public class JavaGetRandomKeyValueElementFromMapExample {

    public static void printRandomMapKeyValueElement() {
        Map<String, Integer> map = new HashMap<>();
        map.put("A", 1);
        map.put("B", 2);
        map.put("C", 3);
        map.put("D", 4);
        map.put("E", 5);

        Set<String> keySet = map.keySet();
        List<String> keyList = new ArrayList<>(keySet);

        int size = keyList.size();
        int randIdx = new Random().nextInt(size);

        String randomKey = keyList.get(randIdx);
        Integer randomValue = map.get(randomKey);

        System.out.println("key: " + randomKey + ", value: " + randomValue);
    }

    public static void main(String[] args) {
        printRandomMapKeyValueElement(); // key: E, value: 5
        printRandomMapKeyValueElement(); // key: A, value: 1
        printRandomMapKeyValueElement(); // key: D, value: 4
    }
}


Java - random numbers

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.