ski*_*iou 2 methods java-8 java-stream
我有一个函数在a上执行一些流操作(特别是一个过滤器)List.
public List<String> getAndFilterNames(List<Person> people, Predicate<Person> nameFilter){
List<String> allNames = people.stream()
.map(person -> person.getName())
.filter(nameFilter)
.collect(Collectors.toList());
return allNames;
}
Run Code Online (Sandbox Code Playgroud)
我希望能够通过中间流操作(filter,distinct等),并有我的功能运行的终端操作之前执行该操作.就像是:
public List<String> getAndProcessNames(List<Person> people, <intermediate stream operation>){
List<String> allNames = people.stream()
.map(person -> person.getName())
// perform <intermediate stream operation> here
.collect(Collectors.toList());
return allNames;
}
Run Code Online (Sandbox Code Playgroud)
虽然,根据我目前的经验水平,似乎是不可能的.一些中间操作有一个参数(比如filter),有些没有(比如distinct),所以我不能设置一个能处理所有情况的参数类型...我想我可以创建一些签名,但是Function和Supplier.
即便如此,该功能界面与参数的功能需要变化...... filter需要Predicate,map需要Function,并从我的理解,是没有办法来表示一个通用的功能接口.那是对的吗?它们都没有真正的公共类或接口.
那么,到底,看来我最好的选择是公正map和collect,然后运行所需的我流操作的情况下,逐案的基础,如:
public List<String> getNames(List<Person> people){
List<String> allNames = people.stream()
.map(person -> person.getName())
.collect(Collectors.toList());
return allNames;
}
List<Person> employees = // a bunch of people
List<String> employeeNames = getNames(employees);
employeeNames = employeeNames.stream(). // desired operations
Run Code Online (Sandbox Code Playgroud)
编辑:或者,@ perHolger:
public Stream<String> getNamesStream(List<Person> people){
Stream<String> namesStream = people.stream()
.map(person -> person.getName());
return namesStream;
}
List<Person> employees = // a bunch of people
Stream<String> employeeNamesStream = getNamesStream(employees);
employeeNamesStream(). // desired operations
Run Code Online (Sandbox Code Playgroud)
还是有什么我想念的?
Bri*_*etz 11
你需要的是从功能Stream到Stream.例如:
public List<String> processNames(Function<Stream<String>, Stream<String>> f) {
return f.apply(people.stream().map(Person::getName))
.collect(toList());
}
Run Code Online (Sandbox Code Playgroud)
然后调用如下:
List<String> filteredNames = processNames(s -> s.filter(n -> n.startsWith("A")));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
309 次 |
| 最近记录: |