iT邦幫忙

2024 iThome 鐵人賽

DAY 17
0
Software Development

Spring boot 從零到寫出ChatGPT系列 第 17

Spring boot 從零開始 (17) - 程式簡潔就靠學會Lambda (上集)

  • 分享至 

  • xImage
  •  

寫膩for迴圈了嗎?

// for迴圈的寫法
List<String> items = List.of();
for (String item : items) {
}
// forEach寫法
items.forEach(item -> {
});

Lambda應用

Lambda能更方便的處理複雜的資料轉換、比對,重新整理成你需要的樣子。
使用Lambda的第一步須將集合物件List、Set、Map等等轉換成Stream物件再進行操作,過程中可以透過Method References的方式簡化程式

List.of("A", "B", "C", "D").stream().forEach(it -> System.out.print(it));
 // Method References
List.of("A", "B", "C", "D").stream().forEach(System.out::print);

以下介紹常用的方法

map

將集合內的資料轉換內容或是型態

// 將List<String>內容轉換成Book
List<String> list = List.of("A", "B", "C", "D");
list.stream().map(it -> Book.builder().bookId(list.indexOf(it)).name(it).build()).forEach(System.out::print);

flatMap

將集合內的資料扁平化處理

// 合併4個List並且轉成Stream物件後扁平化處理
Stream.of(List.of("A"), List.of("B"), List.of("C"), List.of("D")).flatMap(List::stream).forEach(System.out::print);
// Output ABCD

anyMatch、allMatch

判斷集合內的資料是否符合預期

List.of("A", "B", "C", "D").stream().anyMatch(it -> it.equals("A")); // true
List.of("A", "B", "C", "D").stream().allMatch(it -> it.equals("A")); // false

reduce

將集合根據BinaryOperator合併

List.of("A", "B", "C", "D").stream().reduce("", (a, b) -> a.concat(b)) // ABCD

sorted

根據需求將集合進行排序

List.of("A", "B", "C", "D").stream().sorted(String::indexOf).collect(Collectors.joining()) // DCBA

findAny、findFirst

抓出集合中的資料並用Optional包起來,避免空集合或集合為Null情況

List.of("A", "B", "C", "D").stream().findFirst().get() // A
List.of("A", "B", "C", "D").stream().findAny().get() // ABCD隨機

filter

在集合中篩選要排除/保留的條件

List.of("A", "B", "C", "D").stream().filter(it -> it.equals("A")).forEach(System.out::print); // 保留A

上一篇
Spring boot 從零開始 (16) - Spring boot 內建的 HealthIndicator
下一篇
Spring boot 從零開始 (18) - 程式簡潔就靠學會Lambda (下集)
系列文
Spring boot 從零到寫出ChatGPT30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言