Stream filter() in Java with examples

Syntax:

Stream<T> filter(Predicate<? super T> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.

To see how filter() works, let’s create a Player class:

public class Player {

    private String name;
    private int points;
    private boolean vip;
    //Constructor and standard getters

and create some data to play with:

Player peter = new Player("Peter Parker", 15, false);
Player sarah = new Player("Sarah Johnes", 200, true);
Player charles = new Player("Charles Chaplin", 150, false);
Player mary = new Player("Mary Poppins", 1, true);

List<Player> players = Arrays.asList(peter, sarah, charles, mary);

So, for example if we want to see only VIP players, before Java 8 our filter of players would looks like:

List<Player> vipPlayersJava7 = new ArrayList<>();
for (Player p : players) {
    if (p.isVip()) {
        vipPlayersJava7.add(p);
    }
}

How this can be done with Java 8 ? It is just a matter of single line as follows.

List<Player> vipPlayersJava8 = players.stream()
.filter(v -> v.isVip())
.collect(Collectors.toList());

We have passed a Predicate instance into the filter() method in the form of a Lambda expression.

We can also use a method reference, which is shorthand for a lambda expression:

List<Player> vipPlayerJava8MethodRef = players.stream()
        .filter(Player::isVip)
        .collect(Collectors.toList());

Also, we can use multiple conditions with filter(). For example, filter by VIP status and name:

List<Player> sarahAndVip = players.stream()
        .filter(p -> p.getName().startsWith("Sarah") && p.isVip())
        .collect(Collectors.toList());

Interface Segregation Principle

Clients should not be forced to depend upon interfaces that they do not use.

  • Make fine grained interfaces that are client specific
  • Many client specific interfaces are better than one “general purpose” interface
  • Keep your components focused and minimize dependencies between them
  • Notice relationship to the Single Responsibility Principle?
  • avoid ‘god’ interfaces

Liskov Subsitution Principle

If it looks like a duck and quacks like a duck but it needs batteries, you probably have the wrong abstraction.

  • By Barbara Liskov, in 1998
  • Objects in a program would be replaceable with instances of their subtypes WITHOUT altering the correctness of the program.
  • Violations will often fail the “Is a” test.
  • A Square “Is a” Rectangle
  • However, a Rectangle “Is Not” a Square

Open/Closed Principle

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

  • Your classes should be open for extension
  • But closed for modification
  • You should be able to extend a classes behavior, without modifying it.
  • Use private variables with getters and setters – ONLY when you need them.
  • Use abstract base classes

Difference between HashMap and HashSet in Java


Fatal error: Uncaught Error: Call to a member function id() on array in /home/progra49/public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php:36 Stack trace: #0 /home/progra49/public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php(538): CrayonFormatter::format_code('', Array, Object(CrayonHighlighter)) #1 [internal function]: CrayonFormatter::delim_to_internal(Array) #2 /home/progra49/public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php(516): preg_replace_callback('#()#msi', 'CrayonFormatter...', 'import java.uti...') #3 /home/progra49/public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_highlighter.class.php(166): CrayonFormatter::format_mixed_code('import java.uti...', Object(CrayonLang), Object(CrayonHighlighter)) #4 /home/progra49/public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_highlighter.class.php(186): CrayonHighlighter->process() #5 /home/progra49/public_html/wp-content/plugins/crayon-syntax-highligh in /home/progra49/public_html/wp-content/plugins/crayon-syntax-highlighter/crayon_formatter.class.php on line 36