Alex Mills Alex Mills - 1 year ago 45
Java Question

How to get the String representation of all elements in a Java 8 stream

Using Eclipse and Java -version 1.8

I have this code:

public Stream<Ship> remainingShips() {
return this.b.getShips().stream().filter(s -> !s.isSunk());.

public Stream<Ship> sunkShips() {
return this.b.getShips().stream().filter(s -> s.isSunk());.

I want to print out all the items in the stream, by calling

System.out.println("Sunk ships => " + this.opponent.sunkShips());

but this will just print the stream object, how can I get access to all the items in stream and print each out?

Answer Source

You can iterate over the elements of the Stream and print them :

System.out.println("Sunk ships => ");

Or you can generate a List from the Stream and print it :

System.out.println("Sunk ships => " + this.opponent.sunkShips().collect(Collectors.toList());