Java Common Operation List More Elegant Writing Example than for Loop
- 2021-12-09 08:53:27
- OfStack
Introduction
After using JDK 1.8, most list operations can be written using lambda expressions, which can make the code simpler and develop faster. The following is the common operation of lambda expression on list, which is commonly used in my work.
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; // Subordinate department id
}
List<User> list = new ArrayList<>();
Simple traversal
Before using the lambda expression, if you need to traverse list, use the enhanced for loop as follows:
List<User> list = new ArrayList<>();
for (User u:list) {
System.out.println(u.toString());
}
After using the lambda expression, it can be shortened to 1 line of code:
list.forEach(u-> System.out.println(u.toString()));
Filter List collections that meet a property condition
Taking screening users aged between 15 and 17 as an example, the for loop is written as:
List<User> users = new ArrayList<>();
for (User u : list) {
if (u.getAge() >= 15 && u.getAge() <= 17) {
users.add(u);
}
}
The lambda expression is written as:
List<User> users = list.stream()
.filter(u -> u.getAge() >= 15 && u.getAge() <= 17)
.collect(Collectors.toList());
Getting a property returns a new List collection
Taking obtaining id as an example, sometimes in the project, it may be necessary to query or batch update according to List of user id. At this time, List set of user id is needed, and for loop is written as:
List<Integer> ids = new ArrayList<>();
for (User u:list) {
ids.add(u.getId());
}
The lambda expression is written as:
List<User> users = list.stream()
.filter(u -> u.getAge() >= 15 && u.getAge() <= 17)
.collect(Collectors.toList());
Gets an Map collection with one attribute as key and other attributes or corresponding objects as value
The Map set is constructed with the user id as key (sometimes the user number may be key) and the user corresponding to id as value. The loop writing of for is as follows:
Map<Integer,User> userMap = new HashMap<>();
for (User u:list) {
if (!userMap.containsKey(u.getId())){
userMap.put(u.getId(),u);
}
}
The lambda expression is written as:
Map<Integer,User> map = list.stream()
.collect(Collectors.toMap(User::getId,
Function.identity(),
(m1,m2)->m1));
Function. identity () returns an Lambda expression object with output and input 1, which is equivalent to an t- > An Lambda expression of the form t.
(m1,m2)- > m1 here means that if there are two objects of the same id in list during the conversion of map, the first object is stored in map, which can be written by yourself according to the needs of the project.
A collection of Map grouped by an attribute
Taking the department id as an example, sometimes it is necessary to screen out the personnel under different departments according to the department grouping. If for is used, it is written 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);
}
}
The lambda expression is written as:
List<User> list = new ArrayList<>();
for (User u:list) {
System.out.println(u.toString());
}
0
Other circumstances
You can combine stream () with several operations as needed, such as filtering out users aged 15-17 and grouping them by department. If you use for loop, the code is as follows:
List<User> list = new ArrayList<>();
for (User u:list) {
System.out.println(u.toString());
}
1
Using the lambda expression, the code is as follows:
List<User> list = new ArrayList<>();
for (User u:list) {
System.out.println(u.toString());
}
2
Summarize
The above part is the operation of a single List commonly used in the work of this site, and may encounter more complex scenes in the project. You can combine multiple methods according to your needs. My feeling is that using lambda expression code is more concise and clear. Of course, everyone has their own coding habits, so don't spray if you don't like it.