在 map().flatMap() 上使用单个 flatMap() 是否更好?

Is it better to use a single flatMap() over a map().flatMap()?

我想知道两种平面映射情况之间是否存在显着差异。

案例一:

someCollection
    .stream()
    .map(CollectionElement::getAnotherCollection)
    .flatMap(Collection::stream);

案例二:

someCollection
    .stream()
    .flatMap(element -> element.getAnotherCollection().stream());

应该首选哪一个?这些在性能方面是否更好?

Which one should be preferred?

两者之间的差别非常小,完全取决于您和您的团队 - 选择您觉得更舒服的那个。我会选择第二个选项,它更简洁。

Is any of these better in terms of performance?

从时间复杂度来看,没有。第一个示例涉及创建一些不必要的对象,因此第二个是更合理的选择。 但是,请记住,我们在这里讨论的是微优化。