Tuesday, May 12, 2015

How to use Java 8 Stream API's map() function with a function having more than 2 parameters



To use Java 8 Stream API's map() function

with a function having more than 2 parameters,

you can do as follows:

  public List<Banana> apples2Bananas(List<Apple> apples, AdditionalInfo additionalInfo) {
    Function<Apple, Banana> apple2BananaFunction = new Function<Apple, Banana>() {
      @Override
      public Banana apply(Apple apple) {
        return apple2Banana(apple, additionalInfo);
      }
    };
    return apples.stream().map(apple2BananaFunction).collect(Collectors.toList());
  }

  private Banana apple2Banana(Apple apple, AdditionalInfo additionalInfo) {
    ...
  }

It's sort of currying. Is there any better way to do this?

FIX:

Oops! I found a better way as follows:

  public List<Banana> apples2Bananas(List<Apple> apples, AdditionalInfo additionalInfo) {
    return apples.stream()
        .map(apple -> apple2Banana(apple, additionalInfo))
        .collect(Collectors.toList());
  }

Reference:
http://en.wikipedia.org/wiki/Currying

No comments:

Post a Comment