3

Is there flatMap analogy in Cactoos library? I need exactly what flatMap can, but without streams:

The flatMap() operation has the effect of applying a one-to-many transformation to the elements of the stream, and then flattening the resulting elements into a new stream.

E.g. if I have some values in list, and each value has children items, and I want to get all items from each value, I can use flatMap:

List<Value> values = someValues();
List<Item> items = values.stream()
  .flatMap(val -> val.items().stream()) // val.items() returns List<Item>
  .collect(Collectors.toList());

How to do the same thing using Cactoos instead of streams API?

Kirill
  • 7,580
  • 6
  • 44
  • 95
  • 1
    I haven't used Cactoos but I don't see why there would be. Cactoos seeks to replace non-object-oriented methods and structures. A stream is already an object. `flatMap` is an operation on that object. The only thing here that's not in the spirit of Cactoos is `Collectors.toList()` which I suppose would become something like `new ListCollector<>()` – Michael Jan 31 '19 at 14:27

1 Answers1

4

You can use Joined, it is the equivalent of flattening an Iterable.

For example, you would write:

new Joined<>(new Mapped<>(val -> val.items(), someValues()));
Victor Noël
  • 842
  • 8
  • 14
  • 1
    Thanks, submitted a PR to show it on README https://github.com/yegor256/cactoos/pull/1058 – Kirill Jan 31 '19 at 18:45