2

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!

Azeem
  • 11,148
  • 4
  • 27
  • 40
John_Doe
  • 63
  • 5
  • You probably meant `numbers.add((Number)nrAry[i][j])`. – Arnaud Jan 18 '18 at 10:22
  • This doesn't look like best practice to me. I think it would be better to take an array of `Number`. – Tim Biegeleisen Jan 18 '18 at 10:23
  • Thank you for your comment. It is a task set by my lecturer so I saldy cannot change too much of the actual task. – John_Doe Jan 18 '18 at 10:26
  • This question converts 2d array to list. Please, Look this solution : https://stackoverflow.com/questions/11447780/convert-two-dimensional-array-to-list-in-java – ramazankul Jan 18 '18 at 10:36

2 Answers2

3

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;
}
Eran
  • 387,369
  • 54
  • 702
  • 768
0

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());
    }
Giver
  • 91
  • 2
  • 10