压缩列表列表的3种方法。有理由更喜欢其中之一吗? [英] 3 ways to flatten a list of lists. Is there a reason to prefer one of them?

查看:119
本文介绍了压缩列表列表的3种方法。有理由更喜欢其中之一吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一个如下列表。 CoreResult 的字段类型为列表< Double>

Assume we have a list as follows. CoreResult has a field of type List<Double>.

final List<CoreResult> list = new LinkedList<>(SOME_DATA);

目标是在从每个 CoreResult中提取特定字段后展平列表对象。
以下是3种可能的选择。其中任何一个都优于其他人吗?

The objective is to flatten the list after extracting that specific field from each CoreResult object. Here are 3 possible options. Is any one of them preferable to the others?

选项1 :通过 map()提取字段并在收藏家内展平

Option 1: extract a field via map() and flatten inside collector

final List<Double> A = list.stream().map(CoreResult::getField)
            .collect(ArrayList::new, ArrayList::addAll, ArrayList::addAll);

选项2 :通过地图提取字段(),通过 flatten(),简单收集器

Option 2: extract a field via map(), flatten via flatMap(), simple collector

final List<Double> B = list.stream().map(CoreResult::getField)
            .flatMap(Collection::stream).collect(Collectors.toList());

选项3 :提取字段并通过<$一次拼合c $ c> flatMap(),简单收集器

Option 3: extract a field and flatten in one go via flatMap(), simple collector

final List<Double> C = list.stream().flatMap(
             x -> x.getField().stream()).collect(Collectors.toList());

如果不需要从CoreResult中提取任何字段,那么答案会有所不同吗简单地展平列表< List< Double>>

Would the answer be different if there was no need to extract any field from CoreResult, and instead one wanted to simply flatten a List<List<Double>>?

推荐答案

我不确定每个人的性能,但java流使用的构建器模式的一个重要方面是它允许可读性。我个人认为选项2是最具可读性的。选项3也很好。我会避免选项一,因为它会欺骗集合的扁平化。

I'm not sure about the performance of each one, but an important aspect of the builder pattern utilized by java streams is that it allows for readability. I personally find the option 2 to be the most readable. Option 3 is good, too. I would avoid option one because it kind of "cheats" the flattening of the collection.

将每个方法放在自己的行上,并确定哪个方法最直观易读。我更喜欢第二个:

Put each method on its own line and determine which is the most intuitive to read. I rather like the second one:

final List<Double> B = list.stream()
                           .map(CoreResult::getField)
                           .flatMap(Collection::stream)
                           .collect(Collectors.toList());

这篇关于压缩列表列表的3种方法。有理由更喜欢其中之一吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆