NewToThis NewToThis - 5 months ago 17
Java Question

Find length of all values in an array, not how many there are (Java)

I am trying to get the total length of all values in an array added together. I have the following:

String[] text = {"Why","did","this","not","work","earlier.","it","would","have","been","much","easier","if","it","had"};
int inputTotal = text.length;

This prints out the number 15, as there are 15 values stored in the array. What I am trying to work out is how to get the total of the amount of characters in an array. For example:
String[] text = {"Why","did"}
would be 6, not 2.

Any ideas?


Java 8 gives you a pretty elegant way of doing this - you can stream the array, map each string to its length and reduce the stream to its sum:

long totalLength =;