Home > Software engineering >  divide a number from the available list
divide a number from the available list

Time:12-03

Is there any easiest way to divide the number based on the values available from the Map

ex.

int total = 7;

Map<Integer, Integer> myList = new HashMap<>();
myList.put(0,4);
myList.put(1,2);
myList.put(2,1);
myList.put(3,4);
myList.put(4,3);
myList.put(5,1)
myList.put(6,1)

output keys :  [0,4] which holds [4, 3] values equals to 7

Here I will always pick the highest values from map. so keys [0, 4] is the output instead of [0,1,2]. Is there a convenient way to do this in Java

CodePudding user response:

Yes, you can use the TreeMap class in Java to easily achieve this. TreeMap is a implementation of the Map interface that keeps its entries sorted based on the natural ordering of its keys or on a Comparator provided at construction time. This means that you can retrieve the keys with the highest values in the map by using the lastKey method of the TreeMap class.

Here is an example of how you can use a TreeMap to find the keys with the highest values in your map:

int total = 7;

Map<Integer, Integer> myList = new HashMap<>();
myList.put(0,4);
myList.put(1,2);
myList.put(2,1);
myList.put(3,4);
myList.put(4,3);
myList.put(5,1)
myList.put(6,1)

// Create a TreeMap from the original map to keep the entries sorted
TreeMap<Integer, Integer> sortedMap = new TreeMap<>(myList);

// Find the keys with the highest values in the map
List<Integer> keys = new ArrayList<>();
while (total > 0) {
    // Get the key with the highest value
    int key = sortedMap.lastKey();
    keys.add(key);
    // Decrement the total by the value of the key
    total -= sortedMap.get(key);
    // Remove the key from the map
    sortedMap.remove(key);
}

// keys will now contain [0, 4]

Using a TreeMap in this way allows you to easily find the keys with the highest values in the map without having to manually sort the entries or loop through the map multiple times.

  •  Tags:  
  • java
  • Related