Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

java - What is the point of OptionalInt?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First of all, remember that there might be no value present after the filter method usage (or any that returns a different number of objects like reduce). It is not guaranteed that a value would be always present. That's behind the design of returning something that says that the value might be there instead of null that likely causes errors.

Is it really worth having OptionalInt just for that single return object at the end?

Yes, it is worth it. OptionalInt is a representation of Optional<Integer> that returns a primitive int instead (of course the value must be present). We can say it wraps int. Since boxing is related only to primitives, I guess introducing such object/s is for sake of convenience and boxing operation overhead avoidance.

OptionalInt optionalInt = IntStream.range(0, 10)
        .filter(i -> i > 5)
        .map(i -> i + 1)
        .findAny();
int resultInt1 = optionalInt.getAsInt();  // PROS: explicit method name advantage
Optional<Integer> optional =  IntStream.range(0, 10)
        .filter(i -> i > 5)
        .mapToObj(i -> i + 1)             // CONS: boxing (int -> Integer)
        .findAny();
int resultInt2 = optional.get();          // CONS: boxing (Integer -> int)
                                          // CONS: not explicit method name

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...