出于某種原因,我無法理解如何使用流將這個深度嵌套的列表變成一個新列表。 every A in List<A> contains ->
List<B> where every B contains ->
List<C> where every C contains -> List<String>我嘗試了許多不同的迭代,例如: List<String> newlist = listA.getB()
.stream()
.filter(b -> b.getC()
.stream()
.filter(c -> c.getPeople)
.collect(Collectors.toList())我很困惑......我可以使用 for 循環(huán)輕松做到這一點,但我聽說流簡單易行,我想開始更多地使用它們。
1 回答

ibeautiful
TA貢獻1993條經驗 獲得超6個贊
你應該使用flatMap
:
List<String> newList = listA.stream() // Stream<A> .flatMap(a->a.getB().stream()) // Stream<B> .flatMap(b->b.getC().stream()) // Stream<C> .flatMap(c->c.gtPeople().stream()) // Stream<String> .collect(Collectors.toList()); // List<String>
添加回答
舉報
0/150
提交
取消