John_Doe
John_Doe

Reputation: 63

Collect Numbers from a 2D Array

I would like to wirte a method called collectNums which is supposed to collect all the elements of the type Number from a 2D Object Array. Then I would like to collect all of the elements of type Number in a List and return it.

Here's my code:

public static List<Number> collectNums(Object nrAry[][])
{
    List<Number> numbers = new ArrayList<Number>();
    for(int i = 0; i < nrAry.length; i++) 
    {
        for(int j = 0; j < nrAry[i].length; j++)
        {
            if (nrAry[i][j] instanceof Number) 
            {
                numbers.add(j);
                numbers.add(i);
            }
        }
    }
    return numbers;
}

Please let me know if I have not made myself clear. Thanks everyone!

Upvotes: 2

Views: 78

Answers (2)

Giver
Giver

Reputation: 101

In Java 8 it can be simpler:

public static List<Number> collectNums(Object nrAry[][]) {
        return Arrays.stream(nrAry)
                .flatMap(Arrays::stream)
                .filter(x -> x instanceof Number)
                .map(x -> (Number) x)
                .collect(Collectors.toList());
    }

Upvotes: 0

Eran
Eran

Reputation: 393821

You are collecting the indices of the array instead of the values stored in the array.

public static List<Number> collectNums(Object nrAry[][])
{
   List<Number> numbers = new ArrayList<Number>();
   for(int i=0;i < nrAry.length; i++)  {
       for(int j=0;j < nrAry[i].length; j++) {
            if (nrAry[i][j] instanceof Number)  {
                numbers.add((Number)nrAry[i][j]);
            }
        }
    }
    return numbers;
}

Upvotes: 3

Related Questions