Java-Stream-flatMap

  Leave leave1 = new Leave("1","1",new Date(),CollUtil.newArrayList("A","B"));
  Leave leave2 = new Leave("2","2",new Date(),CollUtil.newArrayList("C","D"));
  Leave leave3 = new Leave("3","3",new Date(),CollUtil.newArrayList("E","F"));
  ArrayList<Leave> leaves = CollUtil.newArrayList(leave1, leave2, leave3);

對於上述代碼,如果我想取出第4個參數的集合如何處理呢?在flatMap之前,我所能想到的就是暴力的遍歷吧,如下:

List<String> resultList = new ArrayList<>();
for (Leave leaf : leaves) {
    resultList.addAll(leaf.getNameList());
}

這樣就將所有的nameList放入一個集合中,但是如果我想用stream流呢?在未了解flatMap前,我可能會用Map,但是map有個問題在於,我想要一個集合,但是Map會生產集合嵌套集合,代碼如下:

List<List<String>> resultList = leaves.stream().map(Leave::getNameList).collect(Collectors.toList());

如果我既想用stream,又想要List<String> resultList呢?flatMap閃亮登場:

 List<String> resultList = leaves.stream()
.flatMap(leave
-> leave.getNameList().stream())
.collect(Collectors.toList());
public static void main(String[] args) {
        ArrayList<String> strings1 = CollUtil.newArrayList("123", "212", "212");
        ArrayList<String> strings2 = CollUtil.newArrayList("abc", "qwe", "qbc");
        List<String> collect = Stream.of(strings1,strings2).flatMap(Collection::stream).collect(Collectors.toList());
}

以上flatMap是將相同類型元素合併到一起,既然能合併到一起,那flatMap能不能將一起的元素拆分開呢?以下是將元素進行拆分:

 ArrayList<String> list = CollUtil.newArrayList("ABC", "DEF", "GHI");
 List<String> collect = list.stream().flatMap(ele -> Stream.of(ele.split(""))).collect(Collectors.toList());

 

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