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

huangapple go评论72阅读模式
英文:

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);
英文:

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&lt;String, String&gt; vocabulary = new LinkedHashMap&lt;String, String&gt;();

	Random random = new Random();
	int number = random.nextInt(ReadExcelFile.lastRowNumber);
	String value = (new ArrayList&lt;String&gt;(vocabulary.values())).get(number);

答案1

得分: 9

keys放进一个列表中,然后随机选择一个:

// 在加载(或更改)后执行一次
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);
英文:

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

// Do once after loading (or changing)
List&lt;String&gt; keyList = new ArrayList&lt;&gt;(vocabulary.keySet());

Random random = new Random();
int number = random.nextInt(vocabulary.size());
String key = keyList.get(number);
String value = vocabulary.get(key);

答案2

得分: 2

你可以按照以下方式进行!

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);
英文:

You can go in the following way!

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

huangapple
  • 本文由 发表于 2020年10月14日 22:37:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/64355692.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定