List common operations are more elegant than for loops

Keywords: R Language data structure list

introduction
After using JDK1.8, most list operations can be written using lamada expressions, which can make the code simpler and develop faster. The following are the common operations of lamada expressions I use in my work on list. I like to collect suggestions.
Taking the user table as an example, the user entity code is as follows:

public class User {
    private Integer id; //id

    private String name; //full name

    private Integer age; //Age

    private Integer departId; //Department id
}

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

Simple traversal
Before using the lamada expression, if you need to traverse the list, you generally use the enhanced for loop. The code is as follows:

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

After using the lamada expression, you can shorten it to one line of code:

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

Filter the List collection that meets the criteria of an attribute
Take the screening of users aged 15-17 as an example. The for loop is written as follows:

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

The lamada expression is written as:

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

Get a property and return a new List collection
Take obtaining id as an example. Sometimes in a project, you may need to query or batch update according to the List of user id. at this time, you need the List set of user id. the for loop is written as follows:

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

The lamada expression is written as:

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

Get the Map collection with an attribute as the key and other attributes or corresponding objects as the value
Take the user id as the key (sometimes it may be necessary to take the user number as the key) and the user corresponding to the id as the value to build the Map set. 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 code

The lamada expression is written as:

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

Function.identity() returns a Lambda expression object whose output is the same as the input, which is equivalent to a Lambda expression in the form of T - > t.
(M1, M2) - > M1 here means that if there are two objects with the same id in the list during map conversion, the first object is stored in the map, which can be written here according to the needs of the project.

A collection of maps grouped by an attribute
Take the Department id as an example. Sometimes it is necessary to filter out the personnel under different departments according to the Department grouping. If the for loop is used, it is as follows:

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 = new ArrayList<>();
            users1.add(u);
            departGroupMap.put(u.getDepartId(),users1);
	}
}
Copy code
 use lamada The expression is written as:

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

Other situations
Multiple operations can be performed in combination with stream() as needed, such as filtering out users aged 15-17 and grouping according to departments. If the for loop is used, the code is as follows:

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 = new ArrayList<>();
			users1.add(u);
			departGroupMap.put(u.getDepartId(),users1);
		}
	}
}
Copy code

Use the lamada expression. The code is as follows:

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

summary
The above part is the common single List operation encountered by Xiaobian in his work. He may encounter more complex scenarios in the project. Multiple methods can be combined as needed. My feeling is that the code using lamada expression is more concise and clear. Of course, everyone has their own coding habits. Don't spray it if you don't like it.

If you think this article is a little helpful to you, give it a compliment. Or you can join my development exchange group: 1025263163 learn from each other, and we will have professional technical Q & A to solve doubts

If you think this article is useful to you, please click star: http://github.crmeb.net/u/defu esteem it a favor!

Posted by ali_2kool2002 on Fri, 29 Oct 2021 17:32:13 -0700