查找HashMap中保存最低整数值的键



我正在为需要学习最常用单词的年轻学生创建一个教育游戏。我随机选择列表中的三个单词,将它们显示在屏幕上,播放三个单词中的一个的录音,然后学生必须选择已经发音的单词。我记下他们每个单词猜了多少遍。这样,我就可以为何时向学生介绍新词设定一个标准。当选出其中三个单词时,我想发音学生接触最少的单词。

我有一个名为words的HashMap,它包含单词,以及学生猜测单词次数的整数值。

HashMap<String,Integer>  words 

它包含10到120个关键字/单词。我想创建一个方法,它将三个哈希映射键作为参数,可以返回所需键中值最低的String/key。

我很难让它按计划运行,我很感激任何帮助。

使用Java 8:可能是最短的解决方案

private String getMinKey(Map<String, Integer> map, String... keys) {
return map.entrySet().stream()
.filter(p -> Arrays.asList(keys).contains(p.getKey()))
.min(Comparator.comparingInt(Map.Entry::getValue)).get().getKey();
}

这个怎么样?

private String getMinKey(Map<String, Integer> map, String... keys) {
String minKey = null;
int minValue = Integer.MAX_VALUE;
for(String key : keys) {
int value = map.get(key);
if(value < minValue) {
minValue = value;
minKey = key;
}
}
return minKey;
}

首先从映射中获取条目集:

Set<Entry<String,Integer>> entries = map.entrySet();

现在将其转储到ArrayList中,这样您就可以对其进行排序:

List<Entry<String,Integer>> sortedEntries = new ArrayList<>(entries);

现在对列表进行排序:

Collections.sort(sortedEntries, /*Define your comparitor here to compare by values */);

现在,您的列表中有按值排序的地图内容,您可以按任意顺序访问它们。

这是user3309578答案的变体static HashMap words=new HashMap();

private static String getMax () {
String minKey = null;
int minValue = Integer.MAX_VALUE;
for (String key : words.keySet()) {
int value = words.get(key);
if (value < minValue) {
minValue = value;
minKey = key;
}
}
return minKey;
}
public static void main (String[] args) {
words.put("a", 2);
words.put("b", 4);
words.put("c", 6);
words.put("d", 8);
words.put("e", 1);
words.put("f", 3);
words.put("g", 5);
words.put("h", 7);
System.out.println(getMax());
}

我做了这个,它可以容纳多个键=

HashMap<String,Integer>hashmap_original=new HashMap<>();
hashmap_original.put("key_1",1);
hashmap_original.put("key_2",4);
hashmap_original.put("key_3",1);
hashmap_original.put("key_4",3);
HashMap<String,Integer>hashmap_result=new HashMap<>();
int int_minium_value = 9999; //put a maxium value that u know your code it wont pass it
for (String String_key:hashmap_original.keySet()) {
int int_compare_value=hashmap_original.get(String_key); //get the value
if (int_compare_value<int_minium_value) {
int_minium_value=int_compare_value;
hashmap_result.clear(); //delete non min values
hashmap_result.put(String_key,int_compare_value);
} else if (int_compare_value==int_minium_value) {
hashmap_result.put(String_key,int_compare_value);
}
}
String result=null;//u can use a ArrayList
for (String key_with_the_lowest_value : hashmap_result.keySet()) {
if (result == null) {
result = key_with_the_lowest_value;
} else {
result=result+","+key_with_the_lowest_value;
}
}

最新更新