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

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

我正在尝试编写一些词汇测试。 LinkedHashMap vocabulary 由词汇组成。它们的键是法语单词,值是英语单词。我已经有了一个 GUI,但我正在努力从词汇表中获取一个随机的法语单词及其位置,以确定输入的单词是否正确。我试着用 ArrayList 来做,但后来我只得到了值,但我还需要键来显示这个人必须翻译哪个词。感谢任何帮助。

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

放入列表,然后随机选择一个:

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

您可以通过以下方式进入!

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