我的一位同事向我提出了一个有趣的问题,但是我找不到一个整洁漂亮的Java 8解决方案。问题是流式传输POJO列表,然后基于多个属性将它们收集在映射中-映射导致POJO发生多次
想象以下POJO:
private static class Customer {
public String first;
public String last;
public Customer(String first, String last) {
this.first = first;
this.last = last;
}
public String toString() {
return "Customer(" + first + " " + last + ")";
}
}
将其设置为List<Customer>
:
// The list of customers
List<Customer> customers = Arrays.asList(
new Customer("Johnny", "Puma"),
new Customer("Super", "Mac"));
备选方案1:Map
在“ stream”之外(或在之外forEach
)使用。
// Alt 1: not pretty since the resulting map is "outside" of
// the stream. If parallel streams are used it must be
// ConcurrentHashMap
Map<String, Customer> res1 = new HashMap<>();
customers.stream().forEach(c -> {
res1.put(c.first, c);
res1.put(c.last, c);
});
备选方案2:创建地图条目并流式传输,然后流式传输flatMap
。海事组织,这有点太冗长,不太容易阅读。
// Alt 2: A bit verbose and "new AbstractMap.SimpleEntry" feels as
// a "hard" dependency to AbstractMap
Map<String, Customer> res2 =
customers.stream()
.map(p -> {
Map.Entry<String, Customer> firstEntry = new AbstractMap.SimpleEntry<>(p.first, p);
Map.Entry<String, Customer> lastEntry = new AbstractMap.SimpleEntry<>(p.last, p);
return Stream.of(firstEntry, lastEntry);
})
.flatMap(Function.identity())
.collect(Collectors.toMap(
Map.Entry::getKey, Map.Entry::getValue));
替代方案3:到目前为止,这是我提出的“最精美”代码的另一种方案,但是它使用的三个参数版本,reduce
并且第三个参数有点不可靠,如在此问题中发现的那样:第三个参数用于“减少”的目的Java 8函数编程中的函数。此外,reduce
由于它正在变异并且并行流可能不适用于以下方法,因此似乎不太适合此问题。
// Alt 3: using reduce. Not so pretty
Map<String, Customer> res3 = customers.stream().reduce(
new HashMap<>(),
(m, p) -> {
m.put(p.first, p);
m.put(p.last, p);
return m;
}, (m1, m2) -> m2 /* <- NOT USED UNLESS PARALLEL */);
如果上面的代码是这样打印的:
System.out.println(res1);
System.out.println(res2);
System.out.println(res3);
结果将是:
{Super =客户(Super Mac),Johnny =客户(Johnny Puma),Mac = Customer(Super Mac),Puma = Customer(Johnny Puma)}
{Super = Customer(Super Mac),Johnny = Customer(Johnny Puma), Mac =客户(超级Mac),Puma =客户(约翰尼·彪马)}
{超级=客户(超级Mac),约翰尼=客户(约翰尼·彪马),Mac =客户(超级Mac),彪马=客户(约翰尼·彪马)}
因此,现在我的问题是:我应该如何以Java 8有序的方式流经List<Customer>
,然后以某种方式将其收集为Map<String, Customer>
将整个事物拆分为两个键(first
AND last
)的地方,即Customer
映射两次。我不想使用任何第三方库,也不想像alt 1一样在流之外使用地图。还有其他不错的选择吗?
我认为您的备选方案2和3可以重写为更清楚:
备选方案2:
Map<String, Customer> res2 = customers.stream()
.flatMap(
c -> Stream.of(c.first, c.last)
.map(k -> new AbstractMap.SimpleImmutableEntry<>(k, c))
).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
备选方案3:reduce
通过更改HashMap来滥用代码。要进行可变减少,请使用collect
:
Map<String, Customer> res3 = customers.stream()
.collect(
HashMap::new,
(m,c) -> {m.put(c.first, c); m.put(c.last, c);},
HashMap::putAll
);
请注意,这些不完全相同。如果键重复,则备选方案2将引发异常,而备选方案3将静默覆盖条目。
如果您想要在重复键的情况下覆盖条目,我个人更喜欢替代方案3。它与迭代解决方案最相似。我希望它的性能更高,因为备选方案2必须在所有扁平化的情况下为每位客户分配大量资金。
但是,通过将条目的产生与其聚合分开,替代方案2与替代方案3相比具有巨大优势。这给您很大的灵活性。例如,如果要更改替代方法2以覆盖重复键上的条目,而不是引发异常,则只需将添加(a,b) -> b
到即可toMap(...)
。如果你决定要收集匹配条目到列表中,您所要做的就是更换toMap(...)
用groupingBy(...)
等。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句