Java8 list<T> to list<object[]>

How to parse Generic to Object[] by using stream? I've had

private static <T> List<Object[]> selectData(List<T> a,
    Predicate<T> predicate) {
    ArrayList<Object[]> tmp = new ArrayList<Object[]>();
    for (T x : a) {
      if (predicate.test(x)) {
        tmp.add(new Object[] { x });
      }
    }   
return tmp;
}

but i want to do something like:

...//    
return a.stream().filter(predicate).collect(Collectors.toList());

but i do not know how to do casting each element to Object[]

Upvotes: 0

Views: 1731

Answers (1)

mhlz
mhlz

Reputation: 3557

You can simply use the map function to do exactly that:

return a.stream()
    .filter(predicate)
    .map(o -> new Object[] { (Object) o })
    .collect(Collectors.toList());

map "maps" each element of the stream to its result of the given function, so that after that call all of the elements in the stream are of the type that the mapping function returned (in this case Object[]).

Upvotes: 5

Related Questions