0

I have a dataset like this:

water, 5
eggs, 3
juice, 7
bread, 4 

i save all of these in

HashMap<String, Integer> dataSet = new LinkedHashMap<String,Integer>();

Now i want to create a function to print the elements from max integer to min:

juice, 7
water, 5
bread, 4
eggs, 3

i think that the easiest way to do this is to create a copy of HashMap dataSet and then i must run the HashMapCopy, find the max, print the max element and the remove it from the list.

private static void printMaxToMin(){
    dataSetCopy = new LinkedHashMap<String,Integer>(dataSet);

}

How can i run all the list, find the max, print the pair of elements with the max value every time and then delete it?

Lee Yaan
  • 547
  • 7
  • 26
  • 1
    Possible duplicate of [Java Map sort by value](http://stackoverflow.com/questions/13852725/java-map-sort-by-value) – niceman May 11 '17 at 18:25

3 Answers3

5

here is one way of sorting by value.

dataSet.entrySet().stream()
          .sorted(Map.Entry.<String, Integer>comparingByValue().reversed())
          .forEach(x -> {
               System.out.println(x.getKey() + ","+ x.getValue());
          });

result:

juice,7
water,5
bread,4
eggs,3
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

Yes, that would certainly work. A bit nicer would be to add all the elements to a list and then sort it.

To do this, make a wrapper class containing a String and an Integer that implements Comparable. For example, using Integer compare and if they are equal String compare.

Thijs Steel
  • 1,190
  • 7
  • 16
0

You can't make a Map sort automatically by a value (unless you create a custom map type). I would recommend sorting the map by its values everytime you need to print the map.

Community
  • 1
  • 1
Cedric
  • 532
  • 5
  • 7