Start learning free

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

Long Words Only in Java: Filtering an Array into a List

Practice Read the full explanation

Given an array of strings words and an integer n, return the words that are longer than n characters.

A word must be strictly longer than n: a word with exactly n characters is left out. Keep the words in the order they have in words. If no word is long enough, the result is empty.

 

Example 1:

Input: words = ["apple", "kiwi", "banana", "fig"], n = 4
Output: ["apple", "banana"]
Explanation: apple has 5 characters and banana has 6. kiwi has exactly 4, so it is left out, and fig has only 3.

Example 2:

Input: words = ["hi", "to", "be"], n = 3
Output: []
Explanation: No word has more than 3 characters.

Example 3:

Input: words = ["go", "went", "gone", "went"], n = 3
Output: ["went", "gone", "went"]
Explanation: Every word longer than 3 characters is kept, a repeated one too, in its original order.

 

Constraints:

  • words has at least one word, and every word is made of lowercase English letters.
  • n is 0 or more.
STEP 1 OF 5
    Ctrl + Enter to check

    JAVA · LOOPS WITH STRINGS, ARRAYS & DICTIONARIES

    Long Words Only in Java, explained

    Problem overview

    The method longWords receives an array of strings, words, and an integer n. It returns a List<String> holding the words that have more than n characters, in the order they had in the array.

    With ["apple", "kiwi", "banana", "fig"] and n = 4 the result is [apple, banana]. "kiwi" has exactly 4 characters, and the rule is strictly longer, so it is left out. With ["hi", "to", "be"] and n = 3 no word qualifies and the result is the empty list [].

    Approach: collect the words that pass a test

    This is a filter. You look at each word once, ask one yes/no question, and keep the word only when the answer is yes. You don't know in advance how many words will pass, so an array, whose size is fixed when it is created, is a poor fit for the answer. A list grows as you add to it, which is why the method returns a List.

    Step by step

    1. Create the result list. List<String> result = new ArrayList<>(); starts empty. The variable's type is the interface List, the object is an ArrayList, and the empty <> lets the compiler fill in String.
    2. Visit every word with an enhanced for loop. Each pass gives you one element of the array in the variable word, from the first to the last.
    3. Test the length. A String reports its number of characters with word.length(), with parentheses, unlike an array's length field. The condition is word.length() > n.
    4. Add the word to result inside the if. add appends at the end, and the loop meets the words in their original order, so the order is preserved without any extra work.
    5. Return the list after the loop. If nothing passed, result is still empty, and an empty list is the right answer.

    The solution in Java

    class Solution {
        public List<String> longWords(String[] words, int n) {
            List<String> result = new ArrayList<>();
            for (String word : words) {
                if (word.length() > n) {
                    result.add(word);
                }
            }
            return result;
        }
    }
    

    A few Java details:

    • length() against length. Strings use a method, arrays use a field: words.length would be the number of words, word.length() is the number of characters.
    • Printing a list. A list prints in square brackets, with elements separated by a comma and a space and no quotes, so the first example prints as [apple, banana] and the second as [].
    • Duplicates stay. A list keeps every element you add. With ["go", "went", "gone", "went"] and n = 3 the result is [went, gone, went]: the repeated word appears twice.
    • Imports. List and ArrayList belong to the java.util package, so a standalone program needs import java.util.*; at the top.

    Edge cases and common mistakes

    • Using >=. That would keep words of exactly n characters. In the first example "kiwi" would wrongly appear in the result.
    • n = 0. Every word has at least one letter, so every word is kept: ["a", "bb"] with n = 0 gives [a, bb].
    • Returning inside the loop. A return there would end the method after the first word. The return belongs after the loop.
    • Returning null for "nothing found". The lesson wants an empty list, which callers can loop over safely.

    Testing

    • ["apple", "kiwi", "banana", "fig"] with n = 4 gives [apple, banana].
    • ["hi", "to", "be"] with n = 3 gives [].
    • ["go", "went", "gone", "went"] with n = 3 gives [went, gone, went].
    • ["a", "bb"] with n = 0 gives [a, bb].
    Keep going with Java650+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free