Languages
[Edit]
EN

Java - get random key value element from hash map

11 points
Created by:
Payne
654

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
    }
}


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - HashMap

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join