-
-
Save gdejohn/91e26d20a95fb2c16d778a908ab5f173 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.lang.Integer.parseInt; | |
import static java.util.Comparator.comparing; | |
import static java.util.stream.Collectors.collectingAndThen; | |
import static java.util.stream.Collectors.minBy; | |
import java.io.IOException; | |
import java.nio.file.Files; | |
import java.nio.file.Paths; | |
import java.util.Map; | |
import java.util.Optional; | |
import java.util.function.BiFunction; | |
import java.util.function.Function; | |
public record Grade(int studentID, String courseTitle, int score) { | |
public Grade(String record) { | |
String[] values = record.split("\\|"); | |
this(parseInt(values[0]), values[1], parseInt(values[2])); | |
} | |
private static <T, K, V, R> Collector<T, ?, Stream<R>> groupingByAndMapping( | |
Function<? super T, ? extends K> key, | |
Collector<? super T, ?, Optional<V>> values, | |
BiFunction<? super K, ? super V, ? extends R> function | |
) { | |
return collectingAndThen( | |
groupingBy(key, values), | |
map -> map.entrySet().stream.flatMap( | |
entry -> entry.getValue().map(value -> function.apply(entry.getKey(), value)).stream() | |
) | |
); | |
} | |
public static void main(String[] args) throws IOException { | |
Files.lines(Paths.get(args[0])).map(Grade::new).collect( | |
groupingByAndMapping( | |
Grade::courseTitle, | |
minBy(comparing(Grade::studentID)), | |
(courseTitle, grade) -> "%s %d%".formatted(courseTitle, grade.score()) | |
) | |
).forEach(System.out::println); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment