Languages
[Edit]
DE

Java - Random Schlüsselwertelement aus der Hash-Map abrufen

3 points
Created by:
Nikki
1722

1. Random Schl├╝sselwertelement aus der Hash-Map generieren

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(); // Taste: E, Wert: 5
        printRandomMapKeyValueElement(); // Taste: A, Wert: 1
        printRandomMapKeyValueElement(); // Taste: D, Wert: 4
    }
}

 

Hey ­čĹő
Would you like to know what we do?
  • Dirask is online IT community for professionals and hobbyist 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.