英文:
How to convert Optional<Integer> to OptionalInt
问题
以下是您要翻译的内容:
我有一个 Optional< Integer > 变量:
// es 是一个 arraylist,rock 是 arraylist 中的一个类
var as = IntStream.range(0,es.size()).boxed()
.filter(i->es.get(i) instanceof Rock)
.max((l1,l2) -> comparator(es,(Rock)es.get(l1),(Rock)es.get(l2)));
在这种情况下,我想要为我的方法返回一个 OptionalInt:
if (as.isPresent()) {return Optionalint.of(as);} // 显然这行不起作用
return OptionalInt.empty();
在这种情况下,我如何将 Optional< Integer > 转换为 OptionalInt?
顺便说一下,我在这个问题中找到了这个链接 https://stackoverflow.com/questions/34713973/how-to-convert-an-optional-to-an-optionalint ,但对我的情况帮助不大,当我这样做时:
Stream.of(as).filter(s -> s != null && s.matches("\\d+"))
.mapToInt(Integer::parseInt).findAny();
它会给我一个错误:方法 matches(String) 在 Optional<Integer> 类型中未定义。
有什么解决方法吗?谢谢!
英文:
I have an Optional< Integer > variable:
//es is an arraylist, rock is a class in the arraylist
var as = IntStream.range(0,es.size()).boxed()
.filter(i->es.get(i) instanceof Rock)
.max((l1,l2) -> comparator(es,(Rock)es.get(l1),(Rock)es.get(l2)));
In that case, I want to return an OptionalInt for my method:
if (as.isPresent()) {return Optionalint.of(as);} //Obviously it is not working
return OptionalInt.empty();
How can I convert Optional< Integer > to OptionalInt in that case?
BTW I found this question https://stackoverflow.com/questions/34713973/how-to-convert-an-optional-to-an-optionalint is not quite helpful in my case, when I do like:
Stream.of(as).filter(s -> s != null && s.matches("\\d+"))
.mapToInt(Integer::parseInt).findAny();
It will give me an error: The method matches(String) is undefined for the type Optional<Integer>
Any idea to solve this? Thanks!
答案1
得分: 1
使用 Optional::map
将值映射为 Optional<OptionalInt>
,然后使用 Optional::orElse
返回该值或空的 OptionalInt.empty()
。我假设方法 comparator
正确工作:
OptionalInt as = IntStream.range(0, es.size()).boxed()
.filter(i -> es.get(i) instanceof Rock)
.max((l1, l2) -> comparator(es, (Rock)es.get(l1), (Rock)es.get(l2)))
.map(OptionalInt::of)
.orElse(OptionalInt.empty());
现在变量 as
是 OptionalInt
的一个实例。
然而,在你的第二个代码片段中不能使用该实例,因为 Stream.of(as)
会得到 Stream<OptionalInt>
,我确定这不是你想要的。这只是从链接答案中复制的片段。请记住,它所包含的值是原始的 int
,而不是 String
。
英文:
Use Optional::map
to map the value into Optional<OptionalInt>
and then use Optional::orElse
to return either it or an empty OptionalInt.empty()
. I assume the method comparator
works correctly:
OptionalInt as = IntStream.range(0, es.size()).boxed()
.filter(i-> es.get(i) instanceof Rock)
.max((l1, l2) -> comparator(es, (Rock)es.get(l1), (Rock)es.get(l2)))
.map(OptionalInt::of)
.orElse(OptionalInt.empty());
Now the variable as
is an instance of OptionalInt
.
However, you cannot use that instance in your second snippet because Stream.of(as)
results in Stream<OptionalInt>
and I am sure it is not what you want. This is just a copied snippet from the linked answer. Remember, the value it holds is a primitive int
, not String
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论