List Common LAMada expression – single list operation

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

At the same time, I participated in the Digitalstar project to win the creative gift package and challenge the creative incentive money

The introduction

With JDK1.8, most list operations can be written using lamada expressions, making the code simpler and faster to develop. The following is a list of common operations that I use in my work with lamada expressions. Taking the user table as an example, the user entity code is as follows:

public class User {
    private Integer id; //id

    private String name; / / name

    private Integer age; / / age

    private Integer departId; // Id of the department
}

List<User> list = new ArrayList<>();
Copy the code

Simple traversal

Before using lamada expressions, if you needed to iterate through a list, you would normally use the enhanced for loop, which looks like this:

List<User> list = new ArrayList<>();
for (User u:list) {
    System.out.println(u.toString());
}
Copy the code

Using the LAMada expression, you can shorten it to a single line of code:

list.forEach(u-> System.out.println(u.toString()));
Copy the code

Filter the List collection that matches the criteria of an attribute

To filter users aged 15-17, for loop is written as:

List<User> users = new ArrayList<>();
for (User u : list) {
	if (u.getAge() >= 15 && u.getAge() <= 17) { users.add(u); }}Copy the code

Lamada expression is written as:

List<User> users = list.stream()
                           .filter(u -> u.getAge() >= 15 && u.getAge() <= 17)
                           .collect(Collectors.toList());
Copy the code

Getting a property returns a new List collection

Taking obtaining ID as an example, sometimes the project may need to perform query or batch update operation according to the List of user ID, at this time, the List set of user ID is needed, and the for loop is written as follows:

List<Integer> ids = new ArrayList<>();
for (User u:list) {
	ids.add(u.getId());
}
Copy the code

The lamada expression is written as:

List<Integer> ids = list.stream()
                           .map(User::getId).collect(Collectors.toList());
Copy the code

Gets a set of maps with one attribute as key and another attribute or corresponding object as value

The Map set is constructed with the user ID as the key (sometimes the user ID may be used as the key) and the user corresponding to the ID as the value. The for loop is written as follows:

Map<Integer,User> userMap = new HashMap<>();
for (User u:list) {
	if (!userMap.containsKey(u.getId())){
		userMap.put(u.getId(),u);
	}
}
Copy the code

The lamada expression is written as:

Map<Integer,User> map = list.stream()
                                     .collect(Collectors.toMap(User::getId, 
                                     Function.identity(),
                                     (m1,m2)->m1));
Copy the code

Function.identity() returns a Lambda expression object whose output is the same as the input, equivalent to a Lambda expression of the form t -> t. (m1,m2)-> m1 If there are two objects with the same ID in the map conversion process, the first object is stored in the map. You can write the first object according to the project requirements.

A collection of maps grouped by an attribute

Take the department ID as an example. Sometimes, you need to group people in different departments. If the for loop is used, the following formula is used:

Map<Integer,List<User>> departGroupMap = new HashMap<>();
for (User u:list) {
	if (departGroupMap.containsKey(u.getDepartId())){
            departGroupMap.get(u.getDepartId()).add(u);
	}else {
            List<User> users1 = newArrayList<>(); users1.add(u); departGroupMap.put(u.getDepartId(),users1); }}Copy the code

Lamada expression is written as:

Map<Integer,List<User>> departGroupMap = list.stream()
                                                                 .collect(Collectors
                                                                 .groupingBy(User::getDepartId));
Copy the code

Other situations

You can do multiple things with stream() as needed, such as filter out users between the ages of 15 and 17 and group them by department. If you use the for loop, the code looks like this:

Map<Integer,List<User>> departGroupMap = new HashMap<>();
for (User u:list) {
	if (u.getAge() >= 15 && u.getAge() <= 17) {
		if (departGroupMap.containsKey(u.getDepartId())){
			departGroupMap.get(u.getDepartId()).add(u);
		}else {
			List<User> users1 = newArrayList<>(); users1.add(u); departGroupMap.put(u.getDepartId(),users1); }}}Copy the code

Using a lamada expression, the code looks like this:

Map<Integer,List<User>> departGroupMap = list.stream()
                                                               .filter(u->u.getAge() >= 15 && u.getAge() <= 17)
                                                               .collect(Collectors.groupingBy(User::getDepartId));
Copy the code

conclusion

The above part is the common operation of a single List encountered by the editor in his work. It may be more complicated in the project, so multiple methods can be combined according to needs. In my opinion, lamada expression code is more concise and clear.