Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

java - What is the point of OptionalInt?


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

1 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...