0

I'm trying to sort a HashMap by value then by key which this post has a great solution...

Sort Hashmap by value and then alphabetically

Using lambdas. Specific line of code...

map.entrySet().stream()
    .sorted(Map.Entry.<String, Integer>comparingByValue()
                    .reversed()
            .thenComparing(Map.Entry.comparingByKey()))
    .forEach(System.out::println);

Is there any way to format the output though? I'd like to handle the formatting as opposed to using the default format output. Is the only way to do this is to override the toString method?

Currently the format is Key=Value but would like it to be Key Value and format the value by a specified number of decimals.

pad11
  • 311
  • 3
  • 9
  • `System.out::println` calls `toString`, so yes, you have to override it. – Juan Carlos Mendoza Feb 01 '18 at 13:43
  • It might help to elaborate on how you'd actually want to format the output. Is the issue the standard out `PrintStream`, or is it purely a question of format? – Mena Feb 01 '18 at 13:43
  • Ok Juan. Mena, I updated the post to reflect what I want. – pad11 Feb 01 '18 at 13:45
  • Your edit does elaborate a bit, but the"format the value by a specified number of places" still isn't particularly helpful. Maybe try to add an example of the data as you'd like it formatted? – Mena Feb 01 '18 at 13:45
  • 3
    `.forEach(kv -> { System.out.printf("%s %s", kv.getKey(), kv.getValue()); })`? – giorgiga Feb 01 '18 at 13:48
  • I meant double sorry - it's early :). giorgiga, i'll give that a try thanks! – pad11 Feb 01 '18 at 13:49
  • yep :) - @giorgiga add answer :) .forEach(kv -> { System.out.printf("%s %.1f\n", kv.getKey(), kv.getValue()); }) – pad11 Feb 01 '18 at 13:59

0 Answers0