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)?
Asked
Active
Viewed 1,199 times
0

bad
- 92
- 10
-
1Yes. You can sums up the length of all teams – Zaheer Khorajiya Sep 18 '15 at 10:46
-
Check http://stackoverflow.com/questions/4441099/how-do-you-count-the-elements-of-an-array-in-java – Anonymous Coward Sep 18 '15 at 10:47
2 Answers
3
You can do it with streams:
long players = Arrays.stream(teams).flatMap(team -> Arrays.stream(team)).count();

OldCurmudgeon
- 64,482
- 16
- 119
- 213
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