2

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?

apophis
  • 374
  • 3
  • 11
Alexander Mills
  • 90,741
  • 139
  • 482
  • 817

1 Answers1

6

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

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

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

System.out.println("Sunk ships => " + this.opponent.sunkShips().collect(Collectors.toList());
Eran
  • 387,369
  • 54
  • 702
  • 768
  • thanks! what if I want to print the stream only if the stream has more than 0 items? is there a good way to do that with streams/filters in Java? – Alexander Mills Sep 19 '16 at 06:11
  • 1
    @AlexMills In order to find if a Stream is empty, you have to use some terminal operation (such as `findAny()` or `findFirst()`, which will close the Stream. Therefore I suggest you produce a List (`List ships = this.opponent.sunkShips().collect(Collectors.toList();`) and print it if it's not empty. – Eran Sep 19 '16 at 06:15
  • 5
    There is no point in collecting into a `List` when you already know that you are only interested in a `String` representation. You can use, e.g. `.map(Object::toString).collect(Collectors.joining(", "))`… – Holger Sep 19 '16 at 12:49