2017-07-31 64 views

回答

-1
Map<Integer, Long> map = a.getB().stream() 
    .flatMap(x -> x.getC().stream()) 
    .map(C::getPort) 
    .collect(Collectors.groupingBy(x -> x, Collectors.counting())); 

合并所有C成一个流,并映射到port然后按port

更新:

a.getB().stream() 
    .map(x -> x.getC().stream() 
     .map(C::getPort) 
     .distinct() 
     .collect(Collectors.toList())) 
    .flatMap(Collection::stream) 
    .collect(Collectors.groupingBy(x -> x, Collectors.counting()));`` 
+0

它通过端口分组并得到端口的数量。 OP说**我想按端口分组并获得对象B的数量** – saka1029

+0

这是我的错误。有更新。 – user2256235

-1

这取决于如果B可有重复ç元件或没有。

如果B不能有重复Ç元素:

IntStream Integer> ports = a.b.stream().flatMap(bElem -> bElem.c.stream()).map(cElem -> Integer.valueOf(cElem.port)); 

Map<Integer, Long> countByPort = ports.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()); 

如果B可有重复Ç元素:

实现C等于基于端口/哈希码的方法。然后,只需在“端口”流分配中做一些小改动:

IntStream Integer> ports = a.b.stream().flatMap(bElem -> bElem.c.stream().distinct()).map(cElem -> Integer.valueOf(cElem.port)); 

注意“不同”。

编辑:好吧,我收到任何原因的否定。因此,将试图解释为什么这实际上计算每个特定端口的B的数量,这是用户要求的。首先我们列出所有B中的所有端口。 B上的每个存在都是列表中的一个条目(所以同样的端口会出现在包含它的Bs上的次数)。然后,我只是统计每个端口在该列表中存在的次数。 这是被包括烧烤阿尔泽特端口的数目上

+0

为什么是负面的?没有解决用户问什么? –

0

以下流返回所需的值:

Map<Integer, Long> countMap = a.getB().stream() 
      .flatMap(b -> b.getC().stream().distinct()) 
      .map(C::getPort) 
      .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); 

a.getB().stream())开始的B秒的流。
flatMap(b->b.getC())单位B S其中每个元素包含List<C>CStream A S和删除重复,以避免与在同一端口计数单B两次,当其具有多个C秒的流。请确保,C s等于只比较端口。
后来我map每个C到一个端口和
collect,由int port分组(这是现在identity),成为在返回Map的关键,它的出现次数的计数。