簡單聚合操作

2021-10-01 06:04:00 字數 2455 閱讀 3477

要了解聚合操作,首先要建立stream和管道的概念

stream 和collection結構化的資料不一樣,stream是一系列的元素,就像是生產線上的罐頭一樣,一串串的出來。

管道指的是一系列的聚合操作。

管道又分3個部分

管道源:在這個例子裡,源是乙個list

中間操作: 每個中間操作,又會返回乙個stream,比如.filter()又返回乙個stream, 中間操作是「懶」操作,並不會真正進行遍歷。

結束操作:當這個操作執行後,流就被使用「光」了,無法再被操作。所以這必定是流的最後乙個操作。 結束操作不會返回stream,但是會返回int、float、string、 collection或者像foreach,什麼都不返回, 結束操作才進行真正的遍歷行為,在遍歷的時候,才會去進行中間操作的相關判斷

管道源把collection切換成管道源很簡單,呼叫stream()就行了。

heros.stream()

但是陣列卻沒有stream()方法,需要使用

arrays.stream(hs)

或者stream.of(hs)

每個中間操作,又會返回乙個stream,比如.filter()又返回乙個stream, 中間操作是「懶」操作,並不會真正進行遍歷。

中間操作比較多,主要分兩類

對元素進行篩選 和 轉換為其他形式的流

對元素進行篩選:

filter 匹配

distinct 去除重複(根據equals判斷)

sorted 自然排序

sorted(comparator) 指定排序

limit 保留

skip 忽略

轉換為其他形式的流

maptodouble 轉換為double的流

map 轉換為任意型別的流

public static void main(string args) 

//製造乙個重複資料

heros.add(heros.get(0));

system.out.println("初始化集合後的資料 (最後乙個資料重複):");

system.out.println(heros);

system.out.println("滿足條件hp>100&&damage<50的資料");

heros

.stream()

.filter(h->h.hp>100&&h.damage<50)

.foreach(h->system.out.print(h));

system.out.println("去除重複的資料,去除標準是看equals");

heros

.stream()

.distinct()

.foreach(h->system.out.print(h));

system.out.println("按照血量排序");

heros

.stream()

.sorted((h1,h2)->h1.hp>=h2.hp?1:-1)

.foreach(h->system.out.print(h));

system.out.println("保留3個");

heros

.stream()

.limit(3)

.foreach(h->system.out.print(h));

system.out.println("忽略前3個");

heros

.stream()

.skip(3)

.foreach(h->system.out.print(h));

system.out.println("轉換為double的stream");

heros

.stream()

.maptodouble(hero::gethp)

.foreach(h->system.out.println(h));

system.out.println("轉換任意型別的stream");

heros

.stream()

.map((h)-> h.name + " - " + h.hp + " - " + h.damage)

.foreach(h->system.out.println(h));

}

當進行結束操作後,流就被使用「光」了,無法再被操作。所以這必定是流的最後乙個操作。 結束操作不會返回stream,但是會返回int、float、string、 collection或者像foreach,什麼都不返回,。

結束操作才真正進行遍歷行為,前面的中間操作也在這個時候,才真正的執行。

常見結束操作如下:

foreach() 遍歷每個元素

toarray() 轉換為陣列

min(comparator) 取最小的元素

max(comparator) 取最大的元素

count() 總數

findfirst() 第乙個元素

mongoTemplate聚合操作

準備資料 customer 集合,資料型別如下 只是部分資料,資料量太多就不一一列出 1 通過mongotemplate.group方法 public groupbyresultsgroup string inputcollectionname,groupby groupby,classentity...

聚合索引和非聚合索引簡單介紹

其實,我們的漢語字典的正文本身就是乙個聚集索引。比如,我們要查 安 字,就會很自然地翻開字典的前幾頁,因為 安 的拼音是 an 而按照拼音排序漢字的字典是以英文本母 a 開頭並以 z 結尾的,那麼 安 字就自然地排在字典的前部。如果您翻完了所有以 a 開頭的部分仍然找不到這個字,那麼就說明您的字典中...

簡單組網(配置 VLAN 聚合)

某公司擁有多個部門且位於同一網段,為了提公升業務安全性,將不同部門的使用者劃分到不同 vlan 中。現由於業務需要,不同部門間的使用者需要互通。可以在 switch 上部署 vlan 聚合,實現 vlan101 和 vlan102 二層隔離 三層互通,同時 vlan101 和 vlan102 採用同...