Home > OS >  Is there a way to apply a function with multiple parameters to a stream?
Is there a way to apply a function with multiple parameters to a stream?

Time:09-15

I have the following generic method for transforming a page object into a Slice:

    public static <T,R> Slice<R> toSlice(final Page<T> source, Function<T,R> transform) {
      return Slice.<R>builder()
          .totalPages(BigInteger.valueOf(source.getTotalPages()))
          .pageData(source.stream()
              .map(transform)
              .collect(Collectors.toList()))
          .build();
    }

I would then use this as follows:

return SliceFactory.toSlice(
            someDao.findAll(
                    predicate,
                    PageRequest.of(page, PAGE_SIZE, Sort.by(Sort.Direction.DESC, DEFAULT_SORTING_PROPERTY))),
            dtoFactory::toSomeDto);

However, I would like to now pass an additional argument to dtoFactory.toSomeDto. I'm not sure how can I turn this into a generic method, similar to the existing toSlice method?

CodePudding user response:

You can only do it as the following below: Your other (variable) which you require to affect the result of map, needs to be an external variable, and not a Function<> input:

public static void main(String[] args){

    String anotherVariableThatAlters = "HelloWorld";

    Function<String,String> defaultFunction = (stringFromStream) -> {
        return stringFromStream   "_"   anotherVariableThatAlters;
    };

    System.out.println(Stream.of("1", "2", "3").map(defaultFunction).collect(Collectors.toList()));

}

[1_HelloWorld, 2_HelloWorld, 3_HelloWorld]

CodePudding user response:

Just call it with param -> dtoFactory.toSomeDto(param, additionalParam) but in that case you have to ensure that additionalParam is effectively immutable.

  • Related