dreamsys software

Java 8 Lambda Expressions Tutorial

Filtering Collections

In this example we are going to show how easy it is to filter results from a Collection. This example again shows the old way vs. the new way.

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

public class UserFilterTest {
  private static List<User> users = Arrays.asList(
      new User(1, "Steve", "Vai", 40),
      new User(4, "Joe", "Smith", 32),
      new User(3, "Steve", "Johnson", 57),
      new User(9, "Mike", "Stevens", 18),
      new User(10, "George", "Armstrong", 24),
      new User(2, "Jim", "Smith", 40),
      new User(8, "Chuck", "Schneider", 34),
      new User(5, "Jorje", "Gonzales", 22),
      new User(6, "Jane", "Michaels", 47),
      new User(7, "Kim", "Berlie", 60)
    );

  public static void main(String[] args) {
    oldJavaWay();
    newJavaWay();
  }

  private static void oldJavaWay() {
    List<User> olderUsers = new ArrayList<User>();

    for (User u : users) {
      if (u.age > 30) {
        olderUsers.add(u);
      }
    }

    printListNewWay("Old way older users", olderUsers);
  }

  private static void newJavaWay() {
    List<User> olderUsers = users.stream().filter(u -> u.age > 30).collect(Collectors.toList());
    printListNewWay("New way older users", olderUsers);
  }

  private static void printListNewWay(String type, List<User> users) {
    System.out.println(type + ":");

    users.forEach(u -> System.out.println("\t" + u));

    System.out.println();
  }
}

This example uses the User class from the previous section. Again we create our list of users and this time we want to get a list of only the users older 30 years. This is simple to do in java, here's how we do it with the old method:

  List<User> olderUsers = new ArrayList<User>();

  for (User u : users) {
    if (u.age > 30) {
      olderUsers.add(u);
    }
  }

That's easy enough, but look how easy it is with lambda expressions:

List<User> olderUsers = users.stream().filter(u -> u.age > 30).collect(Collectors.toList());

That's a lot less boilerplate code and we don't have to use any specific List implementation. We could also make our filter more complex by checking more than one variable:

List<User> olderUsers = users.stream().filter(u -> u.age > 30 || u.lastName.startsWith("S")).collect(Collectors.toList());

With this filter we check both age being over 30 and if the last name starts with an "S".

In the next section we will learn how to pass a function as a parameter to another function.


Prev (Comparator) | Next (Functions As Parameters)


Blog Entries
Blob Entry 1
Blob Entry 2
Blob Entry 3
Blob Entry 4
Blob Entry 5
Blob Entry 6