对一个集合的元素执行操作并迭代结果以执行其他操作 [英] Performing an operation over the elements of one collection and iterating over the result to perform some other operation
问题描述
如果我有2个收藏品,
List<String> domainArr;
List<Person> personArr;
我想对字符串中的每个元素进行一次小的转换然后迭代personArr to
I would like to make a minor transformation on each of the elements in the String and then iterate over the personArr to
List<String> urlArr = strArr.stream()
.map(str -> "https://" + strArr)
.collect(Collectors.toList());
我的方法类似于
List<Person> getPersons(String url){
/*makes a restful call to the url and gets a List of objects for each URL.*/
}
我想迭代来自urlArr的每个url并将其传递给getPersons(url)方法,并且对于每个获得的结果(List),我我想迭代这个人并对这些人进行更多操作,比如
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
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.
我想知道如何在Java 8中实现这一功能。任何指针?
I was wondering how to do this the functional way in Java 8. Any pointers?
推荐答案
您可以使用 flatMap
将 List< T>
的流转换为的平流T
You can use flatMap
to convert your stream of List<T>
into flat stream of 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());
这篇关于对一个集合的元素执行操作并迭代结果以执行其他操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!