Java 8 feature, Lambda, provides features to process List easily.
Model class:
public class User {
private Long id;
private String firstName;
private String lastName;
private int age;
private String city;
private LocalDate dateOfBirth;
// Getter and setter methods
}
List to Map
Key: id of user object
Value: user obeject
Option 1
Map<Long, User> userIdMap = userList.stream().collect(Collectors.toMap(User::getId, x -> x));
Option 2
Map<Long, User> userIdMap = userList.stream().collect(Collectors.toMap(x -> x.getId(), x -> x));
List to Map (Object parameters)
Key: id of user object
Value: first name of user object
Option 1
Map<Long, String> userIdMap = userList.stream().collect(Collectors.toMap(x -> x.getId(), x -> x.getFirstName()));
Option 2
Map<Long, String> userIdMap = userList.stream().collect(Collectors.toMap(User::getId, User::getFirstName));
Key: id of user object
Value: name concatenating first and and last names
Map<Long, String> userFullNameMap = userList.stream().collect(Collectors.toMap(x -> x.getId(), x -> (x.getFirstName() + " " + x.getLastName()) ));
Filter
Filter user object by age
List<User> result = userList.stream()
.filter(x -> x.getAge() > 29)
.collect(Collectors.toList());
Filtered output as List
List<User> result = userList.stream()
.filter(x -> x.getAge() > 29)
.collect(Collectors.toCollection(ArrayList::new));
Filtered output as Set
Set<User> result = userList.stream()
.filter(x -> x.getAge() > 29)
.collect(Collectors.toCollection(HashSet::new));