I\'m creating an educational game for young students who needs to learn the most common words. On random I pick three words of the list, show them on the screen, play an audio r
What about this?
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;
}
This is a variation of the answer of 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());
}
Possibly the shortest solution, with 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();
}
i made this, it can hold multiple keys=
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;
}
}
First get the entry set from the map:
Set<Entry<String,Integer>> entries = map.entrySet();
Now dump that into an ArrayList so you can sort it:
List<Entry<String,Integer>> sortedEntries = new ArrayList<>(entries);
Now sort the list:
Collections.sort(sortedEntries, /*Define your comparitor here to compare by values */);
Your list now has the contents of the map sorted by value, you can access them in whatever order you like.