關於Stream()和Collectors.joining()字符串連接器

工作時發現一個很棒的拼接字符串的方法:

final String[] strs= {"x", "y", "z"};
Stream<String> stream = Stream.of(strs);

// 拼接成 [x, y, z] 形式
String result1 = stream.collect(Collectors.joining(", ", "[", "]"));
// 拼接成 x | y | z 形式
String result2 = stream.collect(Collectors.joining(" | ", "", ""));
// 拼接成 x -> y -> z] 形式
String result3 = stream.collect(Collectors.joining(" -> ", "", ""));

可以代替使用冗長的for循環或者forEach循環,更加有feel~

舉個栗子:

 deptDepthStr = deptNameList.stream().collect(Collectors.joining("/"));

將List中的deptName使用“/”連接符連接起來,下面則是用最原始的for循環寫的 ,一句頂三行,有文化還是很棒啊~~

for (int i = 0; i < deptNameList.size() - 1; i++) {
       description += deptNameList.get(i).getDeptName() + "/";
       }
 description =description + deptNameList.get(deptNameList.size() - 1).getDeptName();

 又是元氣滿滿的一天           啾咪~

 

 

 

========================================分割線===================================================

以下爲查詢資料後的擴展:

List<String> widgetIds = widgets.stream().map(Widget::getWidgetId).collect(Collectors.toList());

解釋下一這行代碼:

  • widgets:一個實體類的集合,類型爲List<Widget>
  • Widget:實體類
  • getWidgetId:實體類中的get方法,爲獲取Widget的id

本來想要獲得wiget的id集合,按照我的思路肯定是遍歷widges,依次取得widgetIds,但是此行代碼更加簡潔,高效

stream()優點

  • 無存儲。stream不是一種數據結構,它只是某種數據源的一個視圖,數據源可以是一個數組,Java容器或I/O channel等。
  • 爲函數式編程而生。對stream的任何修改都不會修改背後的數據源,比如對stream執行過濾操作並不會刪除被過濾的元素,而是會產生一個不包含被過濾元素的新stream。
  • 惰式執行。stream上的操作並不會立即執行,只有等到用戶真正需要結果的時候纔會執行。
  • 可消費性。stream只能被“消費”一次,一旦遍歷過就會失效,就像容器的迭代器那樣,想要再次遍歷必須重新生成。

具體可參考原文博客:https://blog.csdn.net/lidai352710967/article/details/81461119

向大神致敬~~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章