Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 361
Prashant Singh Avatar asked Oct 16 '25 03:10

Prashant Singh


1 Answers

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)

like image 56
Luc Talbot Avatar answered Oct 17 '25 17:10

Luc Talbot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!