Start learning free

LESSON 219 OF 285 · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

Word Lengths in Java: Mapping a List of Strings to Integers

Practice Read the full explanation

Given an ArrayList of strings words, return an ArrayList of integers with the length of every word, in the same order as the words.

The length of a word is the number of letters it has.

 

Example 1:

Input: words = ["I", "love", "pancakes"]
Output: [1, 4, 8]
Explanation: "I" has 1 letter, "love" has 4 and "pancakes" has 8.

Example 2:

Input: words = ["banana", "kiwi", "fig"]
Output: [6, 4, 3]
Explanation: The lengths keep the order of the words: first "banana", then "kiwi", then "fig".

Example 3:

Input: words = ["code"]
Output: [4]
Explanation: One word gives one length.

 

Constraints:

  • words has at least one word.
  • Every word is made of English letters, lowercase or uppercase.
  • The result has one length per word, in the same order as words.
STEP 1 OF 4
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Word Lengths in Java, explained

    Problem overview

    The method wordLengths receives a List<String> named words and returns a List<Integer> with the length of every word, in the same order. The input ["I", "love", "pancakes"] gives [1, 4, 8], and ["banana", "kiwi", "fig"] gives [6, 4, 3]. One word gives a list with one number: ["code"] gives [4].

    Approach: one result per input

    Unlike a filter, nothing is skipped here. Every word produces exactly one number, so the result has the same size as the input. You go through the words once and, for each one, add its length to a new list. Adding at the end keeps the order.

    Step by step

    1. Create the empty result. List<Integer> lengths = new ArrayList<>(); will collect the numbers. The element type is Integer, because generic collections can't hold the primitive int.
    2. Loop over the words. An enhanced for loop works on a List exactly as it does on an array, so for (String word : words) visits every word in order.
    3. Add each length. word.length() is an int, and add stores it in the list. Java wraps the int into an Integer for you; this is called autoboxing.
    4. Return after the loop. A return inside the loop would stop after the first word.

    The solution in Java

    class Solution {
        public List<Integer> wordLengths(List<String> words) {
            List<Integer> lengths = new ArrayList<>();
            for (String word : words) {
                lengths.add(word.length());
            }
            return lengths;
        }
    }
    

    Details worth knowing:

    • Length counts every character. Letter case doesn't matter: ["Hello", "WORLD"] gives [5, 5].
    • Boxed numbers. A List<Integer> holds Integer objects. Printing it shows plain numbers in brackets, like [1, 4, 8].
    • Lists, not arrays. Here the input is a list, so you read its size with words.size() if you need it, and the loop doesn't need an index at all.

    Other ways to write it

    An indexed loop does the same job: for (int i = 0; i < words.size(); i++) with lengths.add(words.get(i).length()) inside gives [1, 4, 8] for the first example. It needs more typing and gives the loop a chance to go off by one, so use it only when you need the index. A stream does it in one expression: words.stream().map(String::length).toList() also gives [1, 4, 8] and returns a list. The loop is what this lesson practises, and it is the version that makes the "one input, one output" idea visible.

    The pattern is the same one the other list lessons use: create an empty collection, loop, add, return. What changes from lesson to lesson is only the question you ask inside the loop. Here there is no question at all: every word is transformed and added.

    Edge cases and common mistakes

    • An empty list. It is outside this lesson's rules, but the code handles it: the loop runs zero times and the method returns [].
    • Returning inside the loop. Only the first length would come back, and the method would never look at the other words.
    • Mixing up length, length() and size(). Strings use length(), lists use size(), arrays use the field length.
    • Building the result as an array. The size is known, but the method's return type is a List, so the natural tool is an ArrayList.

    Testing

    • ["I", "love", "pancakes"] gives [1, 4, 8].
    • ["banana", "kiwi", "fig"] gives [6, 4, 3].
    • ["code"] gives [4].
    • ["Hello", "WORLD"] gives [5, 5].
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free