I have a problem: My HashMap looks like:
[1,2,3,4] , 5
[1,3,3,4] , 2
[1,2,5,4] , -1
[1,2,4,4] , -1
I want to sort this hashmap and it worked! I get a LinkedHashMap
back. What I want is to get the keys with the best 'values'. The best 'values' are the smalles number, in this example -1. Is there a option to get in an int[][]
the keys [1,2,5,4] and [1,2,4,4]
back? For example if the best value is 3 and it occurres 5 times, it should give me the 5 keys back. Equal for only one best value. How could I do that?
HashMap<int[], Double> hashMap = new HashMap<int[], Double>();
value = sortHashMap(hashMap);
int[][] bestKey;
// bestkey = value.getTheKeysWithTheBestValue // how could I do that? :(
// bestKey should be
// [ [1,2,5,4], [1,2,4,4] ]
private LinkedHashMap<int[], Double> sortHashMap(HashMap<int[], Double> hashMap) {
List<Entry<int[], Double>> list = new ArrayList<>(hashMap.entrySet());
list.sort(Entry.comparingByValue());
return list.stream().collect(Collectors.toMap(Entry::getKey, Entry::getValue,
(key1, key2) -> key2, LinkedHashMap::new));
}
General idea:
Use Collections.min(yourMap.values())
to get the min
value, stream over the entry set of your map and filter entries having the same value as the min
value, map entries to keys and collect to array:
int[][] bestKeys = yourMap.entrySet()
.stream()
.filter(entry -> entry.getValue().equals(Collections.min(myMap.values())))
.map(Map.Entry::getKey)
.toArray(int[][]::new);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.