Search code examples
javajava-8mongodb-queryjava-streambson

Convert from Arrays.asList to Array


I have this code as below :

fieldsToFilter.stream()
    .map(e -> Arrays.asList(
        Filters.ne(e, ""),
        Filters.exists(e, true)
     ))
     .toArray(Bson[]::new))

while executing I get java.lang.ArrayStoreException: java.util.Arrays$ArrayList

Filters.exists and Filters.ne return new Bson instances. See the docs.

Any help is appreciated


Solution

  • You can use flatMap instead of map and

    Stream.of instead of Arrays.asList

    Bson[] result = fieldsToFilter.stream()
                       .flatMap(e -> Stream.of(Filters.ne(e, "") , Filters.exists(e, true)))
                       .toArray(Bson[]::new);