0

I'm trying to familiarize myself with streams and lambdas and was interested in seeing how we'd write something like the following in terms of lambdas and streams. While this is the cartesian product and there may be easier ways of doing this, I'd prefer an answer that uses "nested" operations introduced alongside streams like map, filter, collect, etc..

List<String> names = Arrays.asList("Superman", "Batman", "Wonder Woman");
List<String> likes = Arrays.asList("good1", "good2", "good3");
List<String> dislikes = Arrays.asList("bad1", "bad2", "bad3");

List<String> statements = new ArrayList<>();
for (String r : names) {
  for (String s : likes) {
    for (String t : dislikes) {
      statements.add(r + " likes " + s + " and dislikes " + t);
    }
  }
}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
Spectacles
  • 119
  • 3
  • Concat `r + " likes " + s + " and dislikes " + t` every time is very costly, you can preconcat some portion like `r + " likes "` in outer loop this way if you consider efficiency – Eklavya Jul 18 '20 at 07:11

1 Answers1

1

You can use two flatMap operations with a nested map operation.

final List<String> statements = names.stream().flatMap(r->
    likes.stream()
        .flatMap(s -> dislikes.stream()
            .map(t -> r + " likes " + s + " and dislikes " + t))
).collect(Collectors.toList());

Demo!

Unmitigated
  • 76,500
  • 11
  • 62
  • 80