Why I Am Unable to Use Collectors in My Code in Java Stream? [Closed]
import static java.util.stream.Collectors.*;
import java.util.*;
import java.lang.*;
//import java.util.Collections;
public class HelloWorld{

 public static void main(String []args){
    System.out.println("Hello World");
    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
    List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
    }
}

output

/tmp/java_tdo3eB/HelloWorld.java:10: error: cannot find symbol
    List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
                                                                                         ^
  symbol:   variable Collectors
  location: class HelloWorld
 1 error

So i query is why i am unable to use Collectors as i have import that class also

3

It's your imports. Do them like this:

package experiments;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @author Luc Talbot
 */
public class HelloWorld {

 public static void main(String []args){
    System.out.println("Hello World");
    List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
    List<String> filtered = strings.stream()
                                   .filter(string -> !string.isEmpty())                        
                                   .collect(Collectors.toList());
    }
}

Output is:

run: Hello World BUILD SUCCESSFUL (total time: 0 seconds)

4
David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest