Java

Java Stream filter

An example of a stream is:

    pencil, ink, customary, people, cat. cake, forestry

If this stream is to be filtered, to have a result of only words whose length is more than five characters, then the result would be:

pencil, customary, people, forestry

Another example of a stream is:

dog, bat, null, field, country, null, superposition

If this stream is to be filtered so that null values are not present, then the result would be:

dog, bat, field, country, superposition

Yet another example of a stream is:

1, 2, 3, 4, 5, 6, 7, 8

If this stream is to be filtered so that the result does not have any number that is less than or equal to 5, then the result would be:

6, 7, 8

A stream is a sequence of elements. The source of the stream can be an array, a collection or input from the hard disk or network. Filtering a stream means eliminating certain elements based on some criteria. Such criteria, when coded, is a function, and it is called a predicate.

Article Content

Predicate

A predicate is a function that results in true or false. For the stream,

pencil, ink, customary, people, cat, cake, forestry

the filter predicate to have only words whose length is greater than 5, can be:

word -> word.length() > 5

word is a dummy variable and represents each word in the stream. A function like this, with the arrow ->, is called a lambda expression. This function is interpreted as words whose lengths are each greater than 5. The length method of a string class returns the length of the string.

The words are read one-by-one, and for each case, if the length of the word is greater than 5, all that expression (from “word” to 5) would result in true; otherwise, all the expression would result in false.

For the stream,

dog, bat, null, field, country, null, superposition

the filter predicate to have non-null words can be:

word -> word != null

This expression means the word addressed is not null.

For the stream of integers,

1, 2, 3, 4, 5, 6, 7, 8

the filter predicate, to not have any number that is less than or equal to 5, is:

number -> number >= 6

where the number refers to each number (in turn). This means any number chosen should be greater than or equal to 6.

In filtering elements of a stream, it is not only the predicate coding that the programmer has to know. The programmer also has to know what structures produce a stream and how a stream is produced. Array or collection is a source of a stream. Do not forget that computer input/output operations can also produce a stream; however, this article does not address this.

Some Stream producing Structures

Array

Arrays are a class meant to handle arrays. The methods of Arrays take an actual array as one of its arguments. Arrays, as a class, has the following method:

public static <T> List<T> asList(T... a)

This is a static method, meaning the Arrays object is not instantiated. This method returns a list. The list can be considered as an unfiltered or a filtered stream, but it is not a true stream. For example, in the following statement, lst produced from a raw source of integers is like an unfiltered stream:

List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);

The List object has a method to produce an unfiltered stream with the same list elements, but as a stream – see below.

Collection

Examples of a collections are ArrayList and Vector. The List itself is a general-purpose collection.

ArrayList

ArrayList, as a class, has the following method:

default Stream<E> stream()

This method returns a stream object. The following code segment illustrates this:

            ArrayList<String> al = new ArrayList<String>();
            al.add("dog"); al.add("bat"); al.add(null); al.add("field");
            al.add("country"); al.add(null); al.add("superposition");

            Stream<String> stre = al.stream();

stre is an unfiltered stream.

List

The list is actually an interface; it is not a class. However, its object can be returned by the static Arrays method, asList(), as shown above. The List object has the stream() method, which is just like that of the ArrayList object. The following code segment shows how the List object can return a stream:

            Vector<String> vtr = new Vector<String>();
            vtr.add("pencil"); vtr.add("ink"); vtr.add("customary"); vtr.add("people");
            vtr.add("cat"); vtr.add("cake"); vtr.add("forestry");

            List<String> lst = vtr.subList(0, vtr.size());
            Stream<String> stre = lst.stream();

The List object here is returned by the subList() method of the vector.

Note: the Arrays class, the ArrayList class, the Vector class, and the List interface are in the java.util.* package, which should be imported. However, the Stream interface is in the java.util.stream.* package (lowercase ‘s’), which should also be imported.

The filter() Method

So, an ArrayList or a List object can produce a stream using their stream() methods. What can produce a List object? The Arrays class and the Vector class can each produce a List object. The Arrays class uses its asList() method, and the Vector class uses its subList() method.

The Stream is an interface and not a class. The Stream object is returned by the stream method of the List object or ArrayList object. The stream object has the filter() method for filtering. Its argument is the predicate. The new stream returned by the filter method is the filtered stream.

The Stream object has many methods. Two of them are: count() and forEach(). The count() method returns the number of elements in the stream, and the forEach() method is used to scan the stream elements.

The Java program should begin with:

    import java.util.*;
    import java.util.stream.*;

Filtering for Strings greater than a Length

The following code shows how to do this:

            Vector<String> vtr = new Vector<String>();
            vtr.add("pencil"); vtr.add("ink"); vtr.add("customary"); vtr.add("people");
            vtr.add("cat"); vtr.add("cake"); vtr.add("forestry");
            List<String> lst = vtr.subList(0, vtr.size());
            Stream<String> stre = lst.stream();

            Stream<String> strea = stre.filter(word -> word.length() > 5);
            strea.forEach(element -> System.out.print(element + " "));
            System.out.println();

The forEach() method took a lambda function, of which this time, it is not a predicate. The filtered output is:

    pencil customary people forestry

Filtering off null Values

The following code shows how it can be done:

            ArrayList<String> al = new ArrayList<String>();
            al.add("dog"); al.add("bat"); al.add(null); al.add("field");
            al.add("country"); al.add(null); al.add("superposition");
            Stream<String> stre = al.stream();

            Stream<String> strea = stre.filter(word -> word != null);
            strea.forEach(element -> System.out.print(element + " "));
            System.out.println();

The output is:

    dog bat field country superposition

Filtering for Bigger Integers

The following code illustrates this:

            List<Integer> lst = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8);
            Stream<Integer> stre = lst.stream();

            Stream<Integer> strea = stre.filter(number -> number >= 6);
            strea.forEach(element -> System.out.print(element + " "));
            System.out.println();

The output is:

    6 7 8

Conclusion

The Arrays class can produce a List object with its asList() method. The Vector class can produce a List object with its subList() method. The List and ArrayList objects each has the stream() method. The stream method returns the unfiltered stream. The Stream object returned has the filter() method that takes a predicate (criteria for filtering). The filter method returns the filtered stream.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.