这里是Vavr List peekOption的文档
https://www.javadoc.io/doc/io.vavr/vavr/0.10.1/io/vavr/collection/List.html#peekOption--
这里是Vavr可遍历headOption的文档
https://www.javadoc.io/doc/io.vavr/vavr/0.10.1/io/vavr/collection/Traversable.html#headOption--
注射似乎完全一样,所以对于这种用法,我可以使用两者,但哪一个是最好的…?
MyObject myObject = myJavaCollection.stream()
.filter(SomePredicate::isTrue)
.collect(io.vavr.collection.List.collector()) //Collect to vavr list to have vavr methods availables
.peek(unused -> LOGGER.info("some log"))
.map(MyObject::new)
.peekOption() //or .headOption()
.getOrNull();所以我想知道这些方法有什么区别。
发布于 2022-04-01 14:00:58
在Vavr的List (参见https://github.com/vavr-io/vavr/blob/master/src/main/java/io/vavr/collection/List.java)的源代码中,我们有:
/**
* Returns the head element without modifying the List.
*
* @return {@code None} if this List is empty, otherwise a {@code Some} containing the head element
* @deprecated use headOption() instead
*/
@Deprecated
public final Option<T> peekOption() {
return headOption();
}因此,就像您说的,它们所做的完全一样,而且由于不推荐使用peekOption(),所以使用headOption()似乎是应该使用的。
至于使用一种而另一种的理由:
看起来,Vavr List接口定义了一些与堆栈相关的方法(如push、pop、peek等),以便更方便地将列表作为堆栈使用,如果您希望这样做的话。(例如,如果认为列表是堆栈,则使用peekOption(),否则使用headOption() )
然而,这些堆栈方法都是不推荐的--可能是因为总是可以使用非堆栈方法来代替它们。因此,他们可能放弃了“列表也是一个堆栈”的想法--也许是因为他们认为它混合了一些概念,使界面过于庞大(只是猜测)。因此,这一定是headOption()成为首选的原因--所有堆栈方法都不推荐使用。
(普通的Java列表也有堆栈方法,但这是通过接口实现的,所以所有的列表都是堆栈,但是您可以拥有一个不是列表的堆栈。)
发布于 2022-04-01 12:56:00
https://stackoverflow.com/questions/71707079
复制相似问题