Java 8 – Lambda – List Operatoins

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));

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s