【发布时间】:2017-05-29 15:15:58
【问题描述】:
鉴于这个类是用 Java 8 风格编写的,我想看看我是否不需要调用两次流 api:
import java.util.*;
public class Foo {
public static void main(String... args) {
List<Person> persons = new ArrayList<>();
init(persons, Person::new, "John", "Doe");
persons.stream()
.map(Person::getFirstName)
.forEach(System.out::println);
persons.stream()
.map(Person::getLastName)
.forEach(System.out::println);
}
@FunctionalInterface
interface PersonFactory {
Person create(String firstName, String lastName);
}
private static void init(List<Person> persons, PersonFactory factory, String fn, String ln) {
persons.add(factory.create(fn, ln));
}
}
class Person {
private final String firstName;
private final String lastName;
public Person(String fName, String lName) {
this.firstName = fName;
this.lastName = lName;
}
public String getFirstName() {return this.firstName;}
public String getLastName() {return this.lastName;}
}
我想看看我是否可以一口气代替stream 的“人”List。
有什么建议吗?
【问题讨论】:
-
我不明白你的用例。如果你需要遍历列表的所有元素,只需要使用
List.forEach,你甚至不需要一个流。当您需要过滤列表的某些元素或对列表的元素进行一些转换时,流很有用,即将名称以A开头的每个人转换为Frog,然后将它们收集到单独的列表中.
标签: java-8