3

I want to filter the CC addresses of the array and want to collect it to the same array,

FOR EXAMPLE

String[] ccAddress = emails.split(";");
ccAddress = Arrays.stream(ccAddress)
                  .filter(adr -> "".equals(adr) == false)
                  .collect(Collectors.toArray);// ?????

My question is, 'Is there any direct way to collect filtered elements to the array in Java8' ?

NOTE : I know I can simply collect them to List and write list.toArray() to get array but that is not my question.

akash
  • 22,664
  • 11
  • 59
  • 87

1 Answers1

9

Did you checked documentation?

You can use Stream.toArray method:

String[] ccAddress = emails.split(";");
ccAddress = Arrays.stream(ccAddress)
        .filter(addr -> !addr.isEmpty())
        .toArray(String[]::new);
Dmitry Ginzburg
  • 7,391
  • 2
  • 37
  • 48
  • 2
    Did you checked documentation? Yes, but my overcomplicated mind brought me down to the Collector and never thought it can have `toArray` to collect in to array. Thanks. :) – akash Jul 17 '15 at 13:37
  • 1
    @TAsk you may always introduce your own `Collector` in the same manner as `toArray`: https://gist.github.com/ginz/62144450dbc6cf34261a – Dmitry Ginzburg Jul 19 '15 at 21:02
  • 2
    @TAsk: Maybe [this](http://stackoverflow.com/questions/28782165/why-didnt-stream-have-a-tolist-method#comment45848538_28782165) helps understanding why `toArray` is a stream method instead of a collector… – Holger Jul 20 '15 at 09:32