0

Suppose that I have a two dimensional array holding 8 teams (rows) and in each team there is 12-15 players. Is there a way to know the total amount of players exist in String teams[][] (WITHOUT looping)?

bad
  • 92
  • 10

3 Answers3

3

You can do it with streams:

long players = Arrays.stream(teams).flatMap(team -> Arrays.stream(team)).count();
OldCurmudgeon
  • 62,806
  • 15
  • 115
  • 208
2

No there is no native Java functionality for this. There is no way you can calculate this without looping.
So you have to use loop and count element.

Sumit Singh
  • 24,095
  • 8
  • 74
  • 100
1

You have to do it manually. Use something like this:

    int count = 0;
    for(int i = 0; i < teams.length;  i++)
        for(int j = 0; j < teams[i].length; j++)
            if(a[i][j] != null)
                count++;
    return count;

This assumes that fields in the array that do not contain a team member are simply null.

SaphirShroom
  • 90
  • 1
  • 8