Languages
[Edit]
EN

Java - get random key value element from hash map

5 points
Created by:
Marcin
15710

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

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join