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,031 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
-
1possible duplicate of [Getting the array length of a 2D array in Java](http://stackoverflow.com/questions/4000169/getting-the-array-length-of-a-2d-array-in-java) – Sumit Singh Sep 18 '15 at 10:47
-
possible duplicate of [Get the size of a 2D array](http://stackoverflow.com/questions/4111393/get-the-size-of-a-2d-array) – David Herrero Sep 18 '15 at 10:48
3 Answers
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