我有以下結構如何獲得父對象數量,同時使用JAVA 8兒童分組流
class A
{
List<B> b;
}
class B
{
List<C> c;
}
class C
{
int port;
}
我想組由端口,並得到對象B前的數:[443:2](2 B的對象具有與端口443 C對象)
我有以下結構如何獲得父對象數量,同時使用JAVA 8兒童分組流
class A
{
List<B> b;
}
class B
{
List<C> c;
}
class C
{
int port;
}
我想組由端口,並得到對象B前的數:[443:2](2 B的對象具有與端口443 C對象)
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()));``
它通過端口分組並得到端口的數量。 OP說**我想按端口分組並獲得對象B的數量** – saka1029
這是我的錯誤。有更新。 – user2256235
這取決於如果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上的次數)。然後,我只是統計每個端口在該列表中存在的次數。 這是被包括燒烤阿爾澤特端口的數目上
爲什麼是負面的?沒有解決用戶問什麼? –
以下流返回所需的值:
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>
到C
的Stream
A S和刪除重複,以避免與在同一端口計數單B
兩次,當其具有多個C
秒的流。請確保,C
s等於只比較端口。
後來我map
每個C
到一個端口和
collect
,由int port
分組(這是現在identity
),成爲在返回Map
的關鍵,它的出現次數的計數。
顯示您的嘗試並澄清您希望按端口進行分組。 – user1803551