I'd like to ask if there's a way to use different delimiters or prefixes based on key value of streamed map.
Here's my code:
Map<String, Double> averageScoresPerTask...
String summary="\nAverage | " averageScoresPerTask(Stream.of(courseResults.toArray
(new CourseResult[0]))).entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(t->String.format(Locale.US,"%.2f", t.getValue())).collect(Collectors.joining(" | "))
" | " String.format(Locale.US,"%.2f",averageTotalScore) " | " mark(averageTotalScore) " |";
What it prints
Student | Lab 1. Figures | Lab 2. War and Peace | Lab 3. File Tree | Total | Mark |
Eco Johnny |56 |69 |90 | 71.67 | D |
Lodbrok Umberto |70 |95 |59 | 74.67 | D |
Paige Ragnar |51 |68 |57 | 58.67 | F |
Average | 59.00 | 77.33 | 68.67 | 68.33 | D |
Similar problem with students but my question is regarding Average line so please ignore them. Here's how it should look like.
Student | Lab 1. Figures | Lab 2. War and Peace | Lab 3. File Tree | Total | Mark |
Eco Johnny | 56 | 69 | 90 | 71.67 | D |
Lodbrok Umberto | 70 | 95 | 59 | 74.67 | D |
Paige Ragnar | 51 | 68 | 57 | 58.67 | F |
Average | 59.00 | 77.33 | 68.67 | 68.33 | D |
So the "|" are perfectly aligned
CodePudding user response:
You can specify the length of your formatted numbers before and after the comma:
String.format(Locale.US, ".2f", 59.3)
This will make your total formatted number 14 characters long, 2 of that characters will be after the comma, 1 will be the comma itself, that leaves 11 characters for the part before the comma. The number will be right aligned and padded with spaces.
Now you just have to know the length of each heading (you could store it in a list) and adjust that total length for each column. But I think that a stream is not the ideal solution here, I would prefer a loop with an index counter, this way you can access two lists by index (the list of headings or their lengths and the list of values you want to output).
CodePudding user response:
You should align also Strings not only numbers. For student the same, student name have different length. I would extract the part that calculate averageScores as a String.
String averageScores = averageScoresPerTask(Stream.of(courseResults.toArray
(new CourseResult[0]))).entrySet().stream()
.sorted(Map.Entry.comparingByKey())
.map(t->String.format(Locale.US,".2f", t.getValue())).collect(Collectors.joining("|"));
Also don't add spaces on Collectors.joining.
And than use a single String.format like this:
String.format(Locale.US,"\n s|%s| .2f|s","Average",averageScores, averageTotalScore, mark(averageTotalScore));