Nested forEach in Java 8

馋奶兔 提交于 2019-12-25 08:29:34

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!