简体   繁体   中英

How can I get the keys with the 'best' values from a LinkedHashMap

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:

  • iterate over the list
  • if the current value is "better", save the value as the "best" and store the key for this value in an ArrayList "best keys"
  • if the current value is "worse", continue to the next
  • if the current value is equal to the current "best" then append the key to the list of "best keys"

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM