It’s easy to lead a Bohemian life, but it’s hard to make good friends. — Balzac
preface
In our daily work, we have scenarios where we need to manipulate collections almost everywhere, and sometimes the logic is very simple, basically filtering, sorting, aggregating and so on the results of an ArrayList. But is some code to write very long, let a person look very helpless pain, big loop nested small loop, half a day can not find a useful place, a long time to understand, the original is to set some simple operations. Lamdaj I feel can be said to be the most useful tool for collection operations, feel that it is equivalent to SQL for collection operations. With this, a lot of work can be moved to the Java database to do, is not also reduce the database pressure!
The preparatory work
Introducing Maven dependencies
<dependency>
<groupId>com.googlecode.lambdaj</groupId>
<artifactId>lambdaj</artifactId>
< version > 2.3.3 < / version >
</dependency>
First, we create a new UserEntity class and give it three properties, ID, name, and age:
public class UserEntity {
private Long userId;
private String userName;
private Integer age;
We define a set:
List<UserEntity> userList = Lists.newArrayList();
Add (new UserEntity(1L, “xiaoming “, 23));
Userlist. add(new UserEntity(2L, “red “, 24));
Userlist. add(new UserEntity(3L, “小雷”, 25));
Userlist. add(new UserEntity(4L, “xiao Li “, 26));
1. Choose people older than 24
List<UserEntity> userList1 = Lambda.select(userList, Lambda.having(Lambda.on(UserEntity.class).getAge(),
Matchers.greaterThan(23)));
2. Choose the oldest or youngest person
UserEntity userMaxAge = Lambda.selectMax(userList, Lambda.on(UserEntity.class).getAge());
Find the sum of the ages of all the people in the set
int sumAge = Lambda.sum(userList, Lambda.on(UserEntity.class).getAge());
The following are the most common
4, need all the people’s ID, without thinking like this:
List<Long> userIdList = Lists.newArrayList();
for (UserEntity userEntity : userList) {
userIdList.add(userEntity.getUserId());
}
The smart ones just write:
List<Long> userIdList = Lambda.extract(userList, Lambda.on(UserEntity.class).getUserId());
A line of code, is not the sense of code concise, readable
5, column row change problem
Some programmers use the GROUP_CONCAT method in SQL
We’re smart enough to do it:
String userName = Joiner.on(“,”).join(Lambda.extract(userList,
Lambda.on(UserEntity.class).getUserName()));
6. Finally, we may need a data structure such as Map<Long,UserEntity> for one-to-one relationships
Map<Long, UserEntity> userMap = Lambda.index(userList, Lambda.on(UserEntity.class).getUserId());
I write here are very simple examples, I feel the most frequently used method, if you do not know how to start when you encounter a very abnormal set operation in work, you can leave a message here and we will study and discuss together.