简体   繁体   English

如何随机获取 LinkedHashMap 的键和值?

[英]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. LinkedHashMap vocabulary由词汇vocabulary组成。 They key is a french word and the value is an english word.他们的key是一个法语单词,value是一个英语单词。 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.我已经有一个 GUI,但我正在努力从词汇表中随机获取一个法语单词及其位置,以确定输入的单词是否正确。 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.我试图用 ArrayList 来做,但后来我只得到了值,但我还需要密钥来显示该人必须翻译的单词。 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);

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);

You can go in the following way!你可以通过以下方式去!

Map<String, String> myMap = new LinkedHashMap<String, String>();
myMap.put("Bonjour", "Hello");
myMap.put("moi", "me");
myMap.put("tue", "you");
        
List<String> val = new ArrayList<String>(myMap.values());
int randomIndex = new Random().nextInt(val.size());
String randomValue = val.get(randomIndex);
            
System.out.println(randomValue);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM