5

I'm refactoring some usages of Google Guava library to Cactoos library and I'm having difficulty figuring out the equivalent implementation of both Function class and Iterables.transform method, using Cactoos library as a replacement.

Example (from https://github.com/yegor256/rultor/blob/b3e58634d6066f52a2a2c94e44033b37e7e464dd/src/test/java/com/rultor/agents/twitter/TweetsTest.java#L84 ):

new JoinedText(
    " ",
    Iterables.transform(
        repo.languages(),
        new Function() {
            @Override
            public String apply(final Language lang) {
                return String.format("#%s", lang.name());
            }
        }
    )
).asString()

What would be the correct equivalent implementation for both in Cactoos?

yegor256
  • 102,010
  • 123
  • 446
  • 597
Filipe Freire
  • 823
  • 7
  • 21
  • 2
    Why wouldn't you just use `repo.languages().stream().map(Language::name).collect(Collectors.joining(" ")`? – Andy Turner Aug 31 '17 at 11:15
  • I could use that approach. languages is an Iterable of Language, would require conversion from Iterable to stream, which I'm trying to avoid (https://stackoverflow.com/questions/23932061/convert-iterable-to-stream-using-java-8-jdk) – Filipe Freire Aug 31 '17 at 11:23
  • @filfreire If you're using Java 8, why are you so reluctant to use streams? In the SO thread you linked there's a (ugly but working) way to convert `Iterable` to `Stream`. – Grzegorz Rożniecki Aug 31 '17 at 11:29
  • @Xaerxess the reluctance comes from the "ugly but working" approach. I'd have no problem using Stream as an initial approach, but languages variable is an Iterable by default, and I'm trying to reach a work-around solution that wouldn't require the conversion to Stream. – Filipe Freire Aug 31 '17 at 11:42

2 Answers2

4

This should work:

String txt = new JoinedText(
  " ",
  new Mapped<>(
    repo.languages(),
    lang -> String.format("#%s", lang.name())
  )
).asString();
yegor256
  • 102,010
  • 123
  • 446
  • 597
2

For mapped iterable there is https://github.com/yegor256/cactoos/blob/master/src/main/java/org/cactoos/iterable/Mapped.java class. For function, there are plenty of them in the package https://github.com/yegor256/cactoos/tree/master/src/main/java/org/cactoos/func

skapral
  • 1,128
  • 9
  • 26