NewToThis NewToThis - 1 year ago 61
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?

Answer Source

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 =;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download