0

I usually print my ArrayLists such as

colors.forEach(color -> System.out.printf("color: %s ", color));

But I somehow can't apply this to normal Arrays (String[] colors).

How do I apply this expression to normal Arrays?

  • 1
    Have you tried this: `Stream.of(colors).forEach(System.out::println)`. If you are using printf, you need to od this as `Stream.of(colors).forEach(color -> System.out.printf("color: %s", color)` – Prashant Feb 29 '16 at 03:58
  • 1
    Why use streams for this? It's actually *more* verbose than a `for` loop: `for (String color : colors) System.out.printf("color: %s ", color);` – Andreas Feb 29 '16 at 04:29
  • It's a sample case. Where I'm applying it, it's less verbose. – Stanley Dawson Feb 29 '16 at 05:31

2 Answers2

2

Basically you need a way to perform Stream operations on arrays. It's as simple as converting your array to a stream:

    Arrrays.stream(colors).forEach(color -> System.out.printf("color: %s ", color));

For more info on this see Java 8 Stream and operation on arrays

Community
  • 1
  • 1
mcmathews
  • 48
  • 3
1

The Arrays class contains various methods for manipulating arrays, including the static stream() method which returns a sequential Stream with the specified array as its source. For your example, you can use the following code:

Arrays.stream(colors).forEach(color -> System.out.printf("color: %s ", color));
Austin
  • 8,018
  • 2
  • 31
  • 37