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?

3
  • 3
    Might help stackoverflow.com/questions/14830313/… Commented Sep 19, 2016 at 5:22
  • 2
    Can you come up with better title for this question? Something like, "How to print all elements in stream?". Thanks Commented Sep 19, 2016 at 8:19
  • yep can do, have done Commented Sep 19, 2016 at 17:17

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

3 Comments

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?
@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<Ship> ships = this.opponent.sunkShips().collect(Collectors.toList();) and print it if it's not empty.
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(", "))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.