Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print out this stream?

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
like image 545
camelCaseUser Avatar asked Nov 18 '25 02:11

camelCaseUser


2 Answers

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
like image 191
Pushpesh Kumar Rajwanshi Avatar answered Nov 20 '25 18:11

Pushpesh Kumar Rajwanshi


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);
like image 41
Deadpool Avatar answered Nov 20 '25 17:11

Deadpool



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!