11

The IntStream class has map(), mapToObj(), mapToLong() and mapToDouble() methods, but those methods seem to be missing from the OptionalInt class.

Is there a good reason for those methods to be missing?

TBieniek
  • 4,858
  • 2
  • 24
  • 29
  • 6
    Perhaps you should ask why `OptionalInt` doesn't have `map` and `flatMap` as `Optional` does. – Eran Jul 27 '15 at 13:08
  • maybe duplicate of http://stackoverflow.com/questions/22725537/using-java-8s-optional-with-streamflatmap – Astrogat Jul 27 '15 at 13:35
  • 2
    Although it doesn't answer the why (and I guess we'will have to wait a member of the dev team to have the answer), Java 9 will introduce a `stream()` method on Optionals. So you could do `Optional optObj = myOptInt.stream().mapToObj(..).findFirst();` as a workaround. – Alexis C. Jul 27 '15 at 13:51
  • Related: http://stackoverflow.com/questions/29104968/can-i-not-map-flatmap-an-optionalint – tkruse Nov 08 '21 at 00:32
  • You get an `OptionalInt` mostly from `min` &co. So instead of `.min () .stream () .boxed () .map ()` you could say `.boxed () .min () .map ()`. This is still clumsy but a bit less clumsy. – Christopher Yeleighton Feb 26 '23 at 16:07

1 Answers1

1

Rather obtusely you can do

OptionalInt oi = OptionalInt.of(1);
oi.ifPresent(i -> IntStream.of(i).map(j -> j + 1).forEach(System.out::println));

However it is not clear why OptionalInt doesn't have the same methods as IntStream although I note Optional has a subset of Stream

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130