Jul 062017

ADM

Java 8 Streams filter examples

  • 06 July 2017
  • ADM

 

 

 

Java 8 Streams filter examples - images/logos/java.jpg

 

In this tutorial will present the use of streams: filter(), collect(), findAny() and orElse().

filter() and collect()

Classic

Before Java 8 in order to filter a list, you had to loop through all the elements and put the results into a new list.

package com.admfactory.filter;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ClassicFilterExample {
    public static void main(String[] args) {

	System.out.println("Classic Filter Example");
	System.out.println();
	List<String> list = Arrays.asList("Argon", "Xenon", "Krypton", "Neon", "Radon", "Helium");
	System.out.println("List before filter: ");
	System.out.println(list);
	System.out.println();

	List<String> result = getFilterOut(list, "Neon");

	System.out.println("List after filter: ");
	System.out.println(result);

    }

    /**
     * Method to filter out the filter parameter
     * 
     * @param lines
     *            the {@link List} object
     * @param filter
     *            the element to be removed
     * @return a new list of {@link List} object
     */
    private static List<String> getFilterOut(List<String> lines, String filter) {
	List<String> result = new ArrayList<>();
	for (String line : lines) {
	    /** filter out the element */
	    if (!filter.equals(line)) {
		result.add(line);
	    }
	}
	return result;
    }
}

Output

Classic Filter Example

List before filter: 
[Argon, Xenon, Krypton, Neon, Radon, Helium]

List after filter: 
[Argon, Xenon, Krypton, Radon, Helium]

Java 8

Using Java 8 the code will be much simpler and at first, the look might look much complicated.

package com.admfactory.filter;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8FilterExample {
    public static void main(String[] args) {

	System.out.println("Java 8 Filter Example");
	System.out.println();
	List<String> list = Arrays.asList("Argon", "Xenon", "Krypton", "Neon", "Radon", "Helium");
	System.out.println("List before filter: ");
	System.out.println(list);
	System.out.println();

        List<String> result = list.stream()                // convert list to stream
                .filter(line -> !"Neon".equals(line))      // remove the "Neon" element from the list
                .collect(Collectors.toList());             // collect the output and convert stream back to a List
	
	System.out.println("List after filter: ");
	System.out.println(result);

    }

}

Output

Java 8 Filter Example

List before filter: 
[Argon, Xenon, Krypton, Neon, Radon, Helium]

List after filter: 
[Argon, Xenon, Krypton, Radon, Helium]

filter(), findAny() and orElse()

For this will need a simple model class.

package com.admfactory.filter;

public class User {
    private String user;
    private String password;
    private String email;

    private User(String user, String password, String email) {
	this.user = user;
	this.password = password;
	this.email = email;
    }

    public String getUser() {
	return user;
    }

    public void setUser(String user) {
	this.user = user;
    }

    public String getPassword() {
	return password;
    }

    public void setPassword(String password) {
	this.password = password;
    }

    public String getEmail() {
	return email;
    }

    public void setEmail(String email) {
	this.email = email;
    }

}

Classic

Before Java 8 in order to find an object in a list, you had to loop through all the elements and compare the results.

package com.admfactory.filter;

import java.util.Arrays;
import java.util.List;

public class ClassicFindExample {
    public static void main(String[] args) {

	System.out.println("Classic Find Example");
	System.out.println();

	List<User> list = Arrays.asList(
		new User("John", "pass1", "john@mail.com"),
		new User("Emily", "pass2", "emily@mail.com"), 
		new User("Peter", "pass3", "peter@mail.com"));
	System.out.println("Entire list: ");
	System.out.println(list);
	System.out.println();

	User result = find(list, "Emily");

	System.out.println("Find user: Emily");
	System.out.println(result);

    }

    /**
     * Method to find {@ User} object based on a property
     * 
     * @param lines
     *            the {@link List} object
     * @param filter
     *            the element to be removed
     * @return a new list of {@link List} object
     */
    private static User find(List<User> users, String name) {
	for (User user : users) {
	    if (name.equals(user.getName())) {
		return user;
	    }
	}
	return null;
    }
}

Output

Classic Find Example

Entire list: 
[[name: John, password: pass1, email: john@mail.com], [name: Emily, password: pass2, email: emily@mail.com], [name: Peter, password: pass3, email: peter@mail.com]]

Find user: Emily
[name: Emily, password: pass2, email: emily@mail.com]

Java 8

Using Java 8 the code will look like this.

package com.admfactory.filter;

import java.util.Arrays;
import java.util.List;

public class Java8FindExample {
    public static void main(String[] args) {

	System.out.println("Java 8 Find Example");
	System.out.println();

	List<User> list = Arrays.asList(
		new User("John", "pass1", "john@mail.com"),
		new User("Emily", "pass2", "emily@mail.com"), 
		new User("Peter", "pass3", "peter@mail.com"));
	
	System.out.println("Entire list: ");
	System.out.println(list);
	System.out.println();

	User user1 = list.stream() 				// Convert to steam
		.filter(x -> "Emily".equals(x.getName())) 	// find user "Emily" only
		.findAny() 					// If 'findAny' then return the found user
		.orElse(null); 					// If not found, return null

	System.out.println("User Emily");
	System.out.println(user1);
	System.out.println();

	User user2 = list.stream().filter(x -> "Simon".equals(x.getName())).findAny().orElse(null);

	System.out.println(user2);

	System.out.println("User Simon");
	System.out.println(user2);

    }
}

Output

Java 8 Find Example

Entire list: 
[[name: John, password: pass1, email: john@mail.com], [name: Emily, password: pass2, email: emily@mail.com], [name: Peter, password: pass3, email: peter@mail.com]]

User Emily
[name: Emily, password: pass2, email: emily@mail.com]

null
User Simon
null

 

 

 

References