0

How to add index to the function used in the map - java 8.

Currently I am doing :

final int[] position = { 0 };

List<Apple> Apples = request.getOranges().stream()
.map(c -> {
           return Converter.fromOranges(c, position[0]++);
          }).collect(Collectors.toList());


public static Apple fromOranges(Orange orange, int position) {

        Apple Apple = new Apple().builder()
                .AppleId(orange.getId())
                .position(orange.isPositioned() ? position : null )
                .build();

        return Apple;
    }

Can someone tell me a better way of doing this. I need the index to be sent for the position ( request.getOranges() is a list - position is just the index in the list)

Alexis C.
  • 91,686
  • 21
  • 171
  • 177
  • The question is, why do these `Apple`s need to know their position. Or why the `Orange` tells whether the `Apple` will need its position or not. Within the result list, each `Apple` has an intrinsic position anyway—its index within the result list. – Holger May 27 '16 at 09:52

1 Answers1

0

The closest thing to a better solution that's available is the hackish

 IntStream.range(0, request.getOranges().size())
    .mapToObj(i -> Converter.fromOranges(request.getOranges().get(i), i))
    .collect(toList())

But that said: streams really aren't designed to interoperate with indexed operations in the first place, and you may well be better off using a traditional for loop.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413