Search code examples
javajava-streamcollectors

How to format double resulting from stream collectors.averagingInt


I have a map Map<String,Double> as a result of a grouping from java stream, which groups players by team and averaging their age as a solution for the task

group the players by their respective teams and calculate the average age for each team.

Which is:

Map<String,Double> result = players.stream().collect(
            Collectors.groupingBy(Player::getTeam, Collectors.averagingInt(Player::getAge)));

The result map, when printed out for sample values shows something like:

result.entrySet().stream().forEach(System.out::println);

output

Tottenham Hotspur=25.333333333333332
Liverpool=26.333333333333332
Manchester City=23.666666666666668
Arsenal=24.0
Chelsea=25.333333333333332
Manchester United=23.0

I want to limit the decimal part to two decimal places.

I have searched how to round a double which seems some how not trivial in java. But something like the below works for two decimal places:

double value   = 12.34567
double rounded = (double) Math.round(value * 100) / 100;

or alternativley converting it to string with:

String result = String.format("%.2f", value);

I'm ok with both solutions, but I don't know how to combine it in the stream while collecting. Is there a way to have the resulting map limited to two decimal places?


Solution

  • The easiest option is to do it when printing:

    result.entrySet().stream().forEach(entry -> {
      System.out.printf("%s: %.2f%n", entry.key, entry.value);
    });