Search code examples
javaarraylisthashmaplinkedhashmap

How to get they key and value of a LinkedHashMap randomly?


I'm trying to write a little vocabulary test. The LinkedHashMap vocabulary consists of vocabulary. They key is a french word and the value is an english word. I already have a GUI but I'm struggling to get a random french word from the vocabulary and its position to find out if the entered word is right. I tried to do it with an ArrayList but then I only get the value but I also need the key to show which word the person has to translate. Any help is appreciated.

LinkedHashMap<String, String> vocabulary = new LinkedHashMap<String, String>();

    Random random = new Random();
    int number = random.nextInt(ReadExcelFile.lastRowNumber);
    String value = (new ArrayList<String>(vocabulary.values())).get(number);


Solution

  • Put the keys into a list, then pick a random one:

    // Do once after loading (or changing)
    List<String> keyList = new ArrayList<>(vocabulary.keySet());
    
    Random random = new Random();
    int number = random.nextInt(vocabulary.size());
    String key = keyList.get(number);
    String value = vocabulary.get(key);