Featured Post

Applying Email Validation to a JavaFX TextField Using Binding

This example uses the same controller as in a previous post but adds a use case to support email validation.  A Commons Validator object is ...

Thursday, December 11, 2014

Counting Items with Java 8 Streams

With Java 8 Streams, you can count the items a filtered list.  This is a quick post that shows some syntax examples of this new technique.

This code uses an enhanced for loop to keep a running count of items.  When the for loop ends, you're left with a variable that can be returned to the caller.

public Long calculateNumAsked( List<NoteGameItem> questions ) {

    long numAsked = 0L;
    for( NoteGameItem item : questions ) {
       if( item.getAsked() ) {
          numAsked++;
       }  
    }
    return numAsked;

}

This is the same code written using Streams.  Call the stream() method on the Java Collection "questions" to produce a stream object.  Each object in the stream will be sent to a filter (filter()) and gathered in the count() method to produce the returned value.

public Long calculateNumAsked( List<NoteGameItem> questions ) {
 
    long numAsked = questions.
       stream().
       filter(item -> item.getAsked()).
       count();

     return numAsked;
}


This is a similar method but one that makes use of a method in its filter predicate.

public Long calculateNumCorrect( List<NoteGameItem> questions ) {

    long numCorrect = questions.
        stream().
        filter(item -> item.getAsked() && isCorrect(item)).
        count();

    return numCorrect;
}

public boolean isCorrect( NoteGameItem item ) { ... a local method


Functionally, the pre-Java 8 code works the same as the Streams code, so it's not needed to rewrite anything.  This blog post is showing the new syntax which will be more readable as Lambda Expressions and Streams catch on.

No comments:

Post a Comment