library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.collect(Collectors.toList());
How Do I print out the list? I've tried
System.out.println(Collectors.toList());
but it gives me
java.util.stream.Collectors$CollectorImpl@4ec6a292
You need to either get this expression assigned to some list like this,
List<String> lastNameList = library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.collect(Collectors.toList());
And then print it using,
System.out.println(lastNameList);
OR you can directly print it like this,
System.out.println(library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.collect(Collectors.toList()));
You're actually doing this,
System.out.println(Collectors.toList());
Which has nothing to print except an empty object of type Collectors, which is why you are seeing this,
java.util.stream.Collectors$CollectorImpl@4ec6a292
Use foreach() method in List
library.stream()
.map(book -> book.getAuthor())
.filter(author -> author.getAge() >= 50)
.map(Author::getLastName)
.limit(10)
.forEach(System.out::println);
If you want to print collected list here is an example
List<Integer> l = new ArrayList<>();
l.add(10);
l.add(20);
l.forEach(System.out::println);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With