3 回答
TA贡献1757条经验 获得超7个赞
您需要将此表达式分配给这样的列表,
List<String> lastNameList = library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.collect(Collectors.toList());
然后使用打印,
System.out.println(lastNameList);
或者你可以像这样直接打印,
System.out.println(library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.collect(Collectors.toList()));
你实际上正在这样做,
System.out.println(Collectors.toList());
除了收集器类型的空对象外,没有什么可打印的,这就是你看到这个的原因,
java.util.stream.Collectors$CollectorImpl@4ec6a292
TA贡献1789条经验 获得超8个赞
使用foreach()方法在List
library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.forEach(System.out::println);
如果你想打印收集的列表,这里是一个例子
List<Integer> l = new ArrayList<>();
l.add(10);
l.add(20);
l.forEach(System.out::println);
TA贡献1784条经验 获得超8个赞
您可以使用Stream.peek打印50岁以上lastName的authors列表,如下所示:age
List<Book> library = List.of(new Book(new Author("overflow", 100)),
new Book(new Author("stack", 80)),
new Book(new Author("nullpointer", 49)));
// you were ignoring the result of collect
List<String> lastNames = library.stream()
.map(Book::getAuthor)
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.peek(System.out::println) // this would print "overflow" and "stack"
.collect(Collectors.toList());
另外,请注意,如果您的主要目的只是打印名称而不是存储它们,您可以简单地使用forEach而不是collect,它们都是终端操作,只是 collect 具有基于 Stream 类型的返回类型,而 forEach 是void:-
library.stream()
.map(Book::getAuthor)
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.forEach(System.out::println);
以上所有,考虑到使用的对象类似于以下
class Book {
Author author;
Book(Author author) {
this.author = author;
}
// ... getters
}
class Author {
String lastName;
int age;
Author(String lastName, int age) {
this.lastName = lastName;
this.age = age;
}
// ... getters
}
添加回答
举报