一.通过Matcher中的find()方法对list集合进行模糊查询操作
1.创建实体对象:
public class User {
private Integer id;
private String name;
private String password;
public User() {
}
public User(Integer id, String name, String password) {
this.id = id;
this.name = name;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.创建数据以及对数据进行模糊查询操作
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 对List集合中的数据 name, password 进行模糊查询
*/
public class TestList {
public static void main(String[] args) {
List<User> users = Collections.synchronizedList(new ArrayList<User>());
User u1 = new User(1, "李国辉", "1");
User u2 = new User(2, "小辉", "22");
User u3 = new User(3, "李国辉", "33");
User u4 = new User(4, "哈喽", "42");
User u5 = new User(5, "哈哈", "25");
users.add(u1);
users.add(u2);
users.add(u3);
users.add(u4);
users.add(u5);
System.out.println("源数据...");
users.forEach(System.out::println);
System.out.println();
System.out.println("对list集合进行模糊查询操作...");
/**
* 传入模糊查询的参数
*/
Pattern pattern = Pattern.compile("小辉");
Pattern pattern1 = Pattern.compile("2");
List list = new ArrayList();
for(int i=0;i<users.size();i++){
Matcher matcher = pattern.matcher(users.get(i).getName());
Matcher matcher1 = pattern1.matcher(users.get(i).getPassword());
//调用模糊查询方法
if(matcher.find() || matcher1.find()){
list.add(users.get(i));
}
}
list.forEach(System.out::println);
}
}
3.运行结果:
二.通过Matcher中的matches()方法对list集合进行匹配筛选操作
1.使用上面之前的源数据进行测试
public class TestList {
public static void main(String[] args) {
List<User> users = Collections.synchronizedList(new ArrayList<User>());
User u1 = new User(1, "李国辉", "1");
User u2 = new User(2, "小辉", "22");
User u3 = new User(3, "李国辉", "33");
User u4 = new User(4, "哈喽", "42");
User u5 = new User(5, "哈哈", "25");
users.add(u1);
users.add(u2);
users.add(u3);
users.add(u4);
users.add(u5);
System.out.println("源数据...");
users.forEach(System.out::println);
System.out.println();
System.out.println("匹配筛选...");
Pattern pattern1 = Pattern.compile("李国辉");
Pattern pattern2 = Pattern.compile("5");
List list = new ArrayList();
for(int i=0;i<users.size();i++){
Matcher matcher1 = pattern1.matcher(users.get(i).getName());
Matcher matcher2 = pattern2.matcher(users.get(i).getId().toString());
if(matcher1.matches() || matcher2.matches()){
list.add(users.get(i));
}
}
list.forEach(System.out::println);
}
}
2.测试结果:
以上是对Matcher中的两个方法的运用,在项目开发中很重要…