javalambdajava-stream

Java dropWhile not removing item in the List


I have the following code fragment and the output is not removing one last String in the list with character sequence 'c'. dropWhile should remove all the string in list with character sequence 'c'?

final List<String> threeLetters = List.of("abc", "cde", "dea", "dei", "mod", "loc", "bpa");
threeLetters.stream()
    .dropWhile(name -> name.contains("c"))
    .map(name -> name + ", ")
    .forEach(System.out::print);
System.out.println();

The output is

dea, dei, mod, loc, bpa,

I am not satisfied the output contains three letter "loc". I am using java 11.0.14 2022.01.18 LTS. Are there any explanations this could happen?

dei, dea, mod, loc, bpa,


Solution

  • I think filter would be more appropriate in your case. dropWhile drops items as long as a specific condition is true. Once this condition doesn't hold the first time, it will stop dropping thereafter. filter instead removes all items from the stream that do not fulfill the condition.

    In your case,

    abc  -> name.contains("c") is true -> drop
    cde  -> name.contains("c") is true -> drop
    dea  -> name.contains("c") is false -> output and stop dropping
    dei  -> output
    mod  -> output
    loc  -> output
    bpa  -> output
    

    In contrast, filter works as follows:

    abc  -> !name.contains("c") is false -> drop
    cde  -> !name.contains("c") is false -> drop
    dea  -> !name.contains("c") is true -> output
    dei  -> !name.contains("c") is true -> output
    mod  -> !name.contains("c") is true -> output
    loc  -> !name.contains("c") is false -> drop
    bpa  -> !name.contains("c") is true -> output
    

    Consequently, what you probably want is:

    final List<String> threeLetters = List.of("abc", "cde", "dea", "dei", "mod", "loc", "bpa");
    threeLetters.stream()
        .filter(name -> !name.contains("c"))
        .map(name -> name + ", ")
        .forEach(System.out::print);
    System.out.println();
    

    See this answer for another illustrative example.