0
TreeMap<String, Integer> map = new TreeMap<>();
    map.put("apple", 5);
    map.put("orange", 8);
    map.put("pear", 3);
    map.put("watermelon", 10);
    map.put("melon", 1337);

How can I sort all the values in descending order and print them?

1 Answers1

2

TreeMap sorts the entries by keys, not be values, so you would have to do something like this:

map.values().stream().sorted().forEach(System.out::println);
Jaroslaw Pawlak
  • 5,538
  • 7
  • 30
  • 57
  • It's a bit funny to print from a forEach, since it makes no guarantees about execution order in general. It would be safer to use forEachOrdered. – whaleberg Nov 09 '15 at 13:35
  • @whaleberg hmmm? The stream is not parallel. `forEach` will execute in order. – Jaroslaw Pawlak Nov 09 '15 at 13:37
  • It happens to execute in order, but there is no guarantee that the ordering won't change in different versions of Java or different compilers. That's why forEachOrdered exists. It is unlikely that oracle will change the sequential stream, so it's probably safe, but I believe it would be better practice to go with the more explicitly ordered one. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#forEach-java.util.function.Consumer- – whaleberg Nov 09 '15 at 13:59
  • forEach vs forEachOrdered: http://stackoverflow.com/questions/32797579/foreach-vs-foreachordered-in-java-8-stream – Jaroslaw Pawlak Nov 09 '15 at 14:32
  • As that says, "The behavior of this operation is explicitly nondeterministic" it happens to work now for sequential streams, but that's an implementation detail subject to change. – whaleberg Nov 09 '15 at 14:48