3
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

Prashant Singh
  • 113
  • 2
  • 2
  • 9
  • 3
    You've imported the identifiers *within* Collections, `.*`. – jonrsharpe Oct 27 '18 at 16:15
  • 3
    Use `import java.util.stream.Collectors;` – xingbin Oct 27 '18 at 16:16
  • The way you can use it with your current import i.e. [static import](https://stackoverflow.com/questions/162187/what-does-the-static-modifier-after-import-mean) is: `strings.stream().filter(string -> !string.isEmpty()).collect(toList());` – Naman Oct 27 '18 at 17:32

1 Answers1

16

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)

Luc Talbot
  • 324
  • 3
  • 7
  • @LukeTalbot can u tell me doff b/w java.util.stream.Collectors and java.util.stream.Collectors.*.Why i use java.util.stream.Collectors. – Prashant Singh Oct 28 '18 at 12:59
  • Collectors is a class not a package. If Collectors was a package, Collectors.* would be all the classes in Collectors and your code would work. However Collectors.* is empty. You can tell that collector is a class because 1 - It begins with a capital letter. 2 - Your code calls the method .toList() from it. Collector is a class in the package stream. Don't forget to up click my answer - I'm a new contributor and can use the reputation points. – Luc Talbot Oct 28 '18 at 21:45
  • thank you very much @lucTalbot – Prashant Singh Oct 30 '18 at 12:28
  • done sir marked – Prashant Singh Oct 31 '18 at 06:42