Skip to content

Java Stream Guide

Assume we have the following classes,

Java
@Data
public class User {
  private long id;
  private String name;
  private int age;

  private List<Address> address;
}


@Data
public class Address {
  private String postCode;
  private String street;
  private String building;
}
  1. Conver a List of User into a Map with key id

    Java
    List<User> users = getUsers();
    Map<Long, User> userIdMap = users.stream().collect(Collectors.toMap(User::getId, Function.identity))
    
    Function.identity is a predefined method that always return the input parameter itself.

  2. Convert a property of User into a list

    Java
    List<User> users = getUsers();
    // get all user names as a list
    List<String> userNames = users.stream().map(User::getName).toList();
    

  3. Flat map a list property of User into a list

    Java
    List<User> users = getUsers();
    List<Address> addresses = users.stream().map(User::getAddress).flatMap(List::stream).toList();
    

    We also can user flatMap to merge a list of list objects.

  4. Filter by property

    Java
    List<User> users = getUsers();
    List<Address> addresses = users.stream().filter(u -> u.getAge() >= 18).toList();
    

  5. Group By Age

    Java
    // group by age and collect user
    List<User> users = getUsers();
    Map<Integer, List<User>> ageUsers = users.stream().collect(Collectors.groupingBy(User::getAge));
    
    // group by age and collect name
    
    Map<Integer, Set<String>> ageNames = users.stream().collect(Collectors.groupingBy(User::getAge, TreeMap::new, Collectors.mapping(User::getName, Collectors.toSet())));