For example, I have a List of multiple Employee objects. Then I want to do a fuzzy query on the List by the name of the Employee object. Is there a good solution? For example, if I enter a query condition of “wang,” I should return a List containing only Employee1.

List list = new ArrayList();
Employee employee1 = new Employee();
employee1.setName("wangqiang");
employee1.setAge(30);
list.add(employee1);
Employee employee2 = new Employee();
employee2.setName("lisi");
list.add(employee2);
employee2.setAge(25);
Copy the code

A:

public List search(String name,List list){
   List results = new ArrayList();
   Pattern pattern = Pattern.compile(name);
   for(int i=0; i < list.size(); i++){
      Matcher matcher = pattern.matcher(((Employee)list.get(i)).getName());
      if(matcher.matches()){
         results.add(list.get(i));
      }
   }
   return results;
}
Copy the code

Pattern Pattern = pattern.pile (name, pattern.case_insensitive);

Matcher.find () can be used for fuzzy matching

public List search(String name,List list){
   List results = new ArrayList();
   Pattern pattern = Pattern.compile(name);
   for(int i=0; i < list.size(); i++){
      Matcher matcher = pattern.matcher(((Employee)list.get(i)).getName());
      if(matcher.find()){
         results.add(list.get(i));
      }
   }
   return results;
}
Copy the code

List Stream indicates the usage of a Stream

if(StringUtils.isNotBlank(keyword)){
    Pattern pattern = Pattern.compile(keyword,Pattern.CASE_INSENSITIVE);
    results = ruleList.stream().filter(t -> pattern.matcher(t).find()).collect(Collectors.toList());
} else {
    results = ruleList;
}
Copy the code