java-Stream流

y_d_g發表於2024-04-09

lambda表示式

定義:不管是什麼物件,lambda表示式主要關注的是對資料進行了什麼操作。

基本格式
(引數列表)->{ 程式碼 }

1.是一個匿名類並且只有一個抽象介面。(筆記)

例子:
new Thread(new Runnable(){
@Override
public void run(){
system。outprintln("新執行緒中run 方法被執行了")
}
})

new Thread(() ->{ system。outprintln("新執行緒中run 方法被執行了") )

*********************************************************************************************************
Stream流 stream: 篩選 ,去重,轉換,查詢,遍歷
@EqualsAndHashCode //用於後期的去重使用
建立流
1 單列集合:集合物件.stream()
2 陣列: arrays.stream(arr) 或者 stream.of(arr)
3 雙列集合:轉成單列集合後再建立 map.entrySet.stream()
map<String,Integer> map = new HashMap)<>();
map.put("黑子"."17")
map.put("桃子"."17")
map.put("黑子"."17")
map.entrySet.stream()

中間流
.distinct //去重
.filter() //設定條件,滿足條件就留下

.map //可以獲取list中JavaBean的某個欄位,轉成一個新的list。(結果回去 string,int,bool...單個型別的list)

.flatmap 可以將一個流中的每個元素都轉換成一個流,然後把這些流連成一個流,也就是說,它可以把一個流中的流元素“展平”成一個流

.limit (2) 設定流的最大長度,超出的部分將被拋棄
.skip(3) 跳過流中的前N個元素,返回剩下的元素

.sorted((p1, p2) -> p1.getAge().compareTo( p1.getAge()))).collect(Collectors.toList()) 升序
.sorted( new Comparator 方法) 1-3 解釋:1到3 //排序
.sorted(Comparator.comparingInt(Person::getAge).reversed()) .collect(Collectors.toList()) 降序 (reversed()這個方法是降序)

.concat(list1,list2) //倆個list合併

終結流
.forEach 對流中的元素進行遍歷進行具體操作
.collect(Collectors.toList) 把當前流轉成 另一個集合

.count 獲取流中的元素個數
.max( new Comparator) 最大值
.Min ( new Comparator) 最小值


例子
先按年齡排序,在按價格排序 (關鍵字:thenComparing)
.sorted(Comparator.comparingInt(Person::getAge)
.thenComparing(Comparator.comparingInt(Person::getPrice)))
.collect(Collectors.toList()) 降序 (reversed()這個方法是降序)

例子1
flatMap(T -> Stream)
將流中的每一個值轉換成另一個流,再把每一個流連線成為一個流
List<String> list = new ArrayList<>();
list.add("aaa bbb ccc");
list.add("ddd eee fff");
list.add("ggg hhh iii");
list = list.stream().map(s -> s.split(" “)).flatMap(Arrays::stream).collect(toList());

例子1
.collect(Collectors.toMap) 把當前流轉,另一個map
//獲取一個map集合,map的key為作者名,value為List<Book>
List<Author>authors = getAuthors()

authors.stream
key value
.collect(Collectors.toMap(new Function<Autor,String>(){ return author.getName }, new Function<Autor,List<Book>>(){return author.getBooss} ))


例子2
map<String,Integer> map = new HashMap)<>();
map.put("黑子"."17")
map.put("桃子"."17")
map.put("黑子"."17")
map.entrySet.stream()
key value
.collect(Collectors.toMap(new Function<entrySet,String>(){ return entrySet.getKey }, new Function<entrySet,String >(){return entrySet.getValue} ))


筆記:
1.如果沒有終結操作,沒有中間操作是不會得到執行的
2,流是一次性的,一個終結操作後,這個流就不能再被使用了。

相關文章