Static import of Collectors

When working with streams, the Collectors class is often used for the last (or terminal) operation. Since the Collectors class is so commonly used with streams, it's reasonable to expect that the maintainer of your code will be familiar with it.

One of the advantages of code written in the functional programming style is that it's terse, and reads at a high level. Using a static import for the static methods of Collectors will help you retain that concision.

So, habitually using a static import for the Collectors class seems like a good practice.


//these methods are commonly used with streams
import static*;

import java.util.List;
import java.util.function.Predicate;
import java.util.function.ToIntFunction;

/** @since Java 8 */
public final class StaticImportCollectors {
  /** Filter the Atoms somehow, and return them in a List. */
  List<Atom> filter(Predicate<Atom> predicate){
    return Stream.of(Atom.values())
      .collect(toList()) //WITH the static import of Collectors
      //.collect(Collectors.toList()) //WITHOUT the static import
   Filter the Atoms somehow, and summarize by turning each Atom into 
   an int of some sort, and then summing the int's. 
  int filterAndSum(Predicate<Atom> predicate, ToIntFunction<Atom> summarizer){
    int result = Stream.of(Atom.values())
      .collect(summingInt(summarizer)) //WITH the static import of Collectors
      //.collect(Collectors.summingInt(summarizer)) //WITHOUT the static import
    return result;

   Some data from the periodic table of the elements (incomplete!). 
  enum Atom {
    H("Hydrogen", 1, false),
    Tc("Technetium", 43, true),
    Au("Gold", 79, false),
    Pb("Lead", 82, false),
    Pu("Plutonium", 94, true),
    Fm("Fermium", 100, true);
    private Atom(String name, Integer numProtons, Boolean isAlwaysUnstable){ = name;
      this.numProtons = numProtons;
      this.isAlwaysUnstable = isAlwaysUnstable;
    Boolean isAlwaysUnstable() { return isAlwaysUnstable; }
    String getName() { return name;  }
    Integer getNumProtons() { return numProtons; }
    private String name;
    private Integer numProtons;
    private Boolean isAlwaysUnstable;

See Also :
Use static imports rarely