Jack Smith
Jack Smith

Reputation: 53

shifting arrays with nulls/empty elements

I've been reading a lot on arrays and questions on here but couldn't find any answer to this.

I have an array which will equal either:

Toys[][] toys = { {toy, toy, toy, toy}, {toy}, {}, {toy,toy}, {toy} };

or

Toys[][] toys = { {toy, toy, toy, toy}, {toy}, null, {toy,toy}, {toy} };

I'm trying to shift the element(s) after the nulled or empty element to the left so it would equal to this:

 Toys[][] toys = { {toy, toy, toy, toy}, {toy}, {toy,toy}, {toy} };

I've tried streaming values like this:

toys = (Toys[][]) Arrays.stream(toys).filter(i -> !(i == null || i.length == 0)).toArray();

but for some reason it does nothing

Upvotes: 0

Views: 355

Answers (1)

shmosel
shmosel

Reputation: 50716

I think your code is throwing an exception. The zero-argument toArray() method returns Object[], which you're incorrectly casting to Toys[][]. Try this overload instead:

toys = Arrays.stream(toys)
        .filter(i -> !(i == null || i.length == 0))
        .toArray(Toys[][]::new);

Upvotes: 1

Related Questions