Use static imports rarely
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.
Example
//these methods are commonly used with streams import static java.util.stream.Collectors.*; //import java.util.stream.Collectors; import java.util.List; import java.util.function.Predicate; import java.util.function.ToIntFunction; import java.util.stream.Stream; /** @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()) .filter(predicate) .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()) .filter(predicate) .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){ this.name = 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; } }