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;
}
-
Conver a List of User into a Map with key id
JavaList<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. -
Convert a property of User into a list
-
Flat map a list property of User into a list
JavaList<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. -
Filter by property
-
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())));