2017-07-31 25 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的關鍵,它的出現次數的計數。