Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading