问题
I want to rewrite this piece of code in terms of streams from Java 8
for (Medium medium : sortierteMedien) {
System.out.println("Fuenf aehnlichste Medien fuer " + medium.getClass() + " mit dem Titel " + medium.getTitel() + ":\n");
for (Medium medium1 : bibliothek.medienSim(medium)) {
System.out.println(medium1.toString());
}
System.out.println();
}
The difficulty here is, that there is a print
statement before and after each inner for
loop.
Is it possible to rewrite this with streams?
回答1:
Imperative statements within loops aren’t typical tasks for Stream API use. You still could do this using lambda expressions without the Stream API, i.e.
sortierteMedien.forEach(medium -> {
System.out.println("Fuenf aehnlichste Medien fuer "
+medium.getClass()+" mit dem Titel "+medium.getTitel()+":\n");
bibliothek.medienSim(medium).forEach(System.out::println);
System.out.println();
});
It would be a different thing, if you want to collect everything into one String before printing:
String result = sortierteMedien.stream().flatMap(medium -> Stream.concat(
Stream.of("Fuenf aehnlichste Medien fuer "
+medium.getClass()+" mit dem Titel "+medium.getTitel()+":\n"),
bibliothek.medienSim(medium).stream().map(Medium::toString)
))
.collect(Collectors.joining("\n"));
System.out.println(result);
来源:https://stackoverflow.com/questions/41006671/nested-foreach-in-java-8