[英]Performing an operation over the elements of one collection and iterating over the result to perform some other operation
If I have 2 collections, 如果我有2个收藏,
List<String> domainArr;
List<Person> personArr;
I would like to make a minor transformation on each of the elements in the String and then iterate over the personArr to 我想对String中的每个元素进行较小的转换,然后遍历personArr以
List<String> urlArr = strArr.stream()
.map(str -> "https://" + strArr)
.collect(Collectors.toList());
I have a method like 我有一种方法
List<Person> getPersons(String url){
/*makes a restful call to the url and gets a List of objects for each URL.*/
}
I would like to iterate over each of the urls from urlArr and pass it to the getPersons(url) method and for each of the obtained result (a List), I would like to iterate over the person and perform more operations on the persons like 我想遍历urlArr中的每个url并将其传递给getPersons(url)方法,对于每个获得的结果(一个List),我想遍历该人并对诸如此类的人执行更多操作
persons.stream()
.filter(Objects::nonNull)
.map(Person::getName)
.filter(Objects::nonNull)
.collect(Collectors.toList());
I am hoping to have all the person names here from all the results. 我希望从所有结果中得到所有人员的姓名。
I was wondering how to do this the functional way in Java 8. Any pointers? 我想知道如何在Java 8中以功能方式进行操作。是否有指针?
You can use flatMap
to convert your stream of List<T>
into flat stream of T
您可以使用flatMap
将List<T>
流转换为T
平面流
strArr.stream()
.map(str -> "https://" + strArr)
.map(url -> getPersons(url))
.flatMap(persons -> persons.stream())
.filter(Objects::nonNull)
.map(Person::getName)
.filter(Objects::nonNull)
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.