Skip to content

Instantly share code, notes, and snippets.

@gdejohn
Last active December 14, 2021 16:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gdejohn/91e26d20a95fb2c16d778a908ab5f173 to your computer and use it in GitHub Desktop.
Save gdejohn/91e26d20a95fb2c16d778a908ab5f173 to your computer and use it in GitHub Desktop.
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