Implementation of fuzzy query in java List

  • 2020-05-17 05:25:50
  • OfStack

So let's say I have an List like this, where I have multiple Employee objects. Then I want to do a fuzzy query on this 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 of 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);

Method 1:


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;
}

The one above is case sensitive. If case insensitive is required, change it to:

Pattern pattern = Pattern.compile(name,Pattern.CASE_INSENSITIVE);

And the above is an exact query, so if you want a fuzzy match, matcher.find () will do the fuzzy match


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;
}

Method 2:


public class ListLike {

// Define employee class 
public class Employee {
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

public List list=new ArrayList();

// To increase staff 
public List addList(String name,int age){
Employee employee1 = new Employee();
employee1.setName(name);
employee1.setAge(age);
list.add(employee1);
return list;
}

// Show all employees 
public void ShowList(){
for(int i=0;i<list.size();i++){
System.out.println(((Employee)(list.get(i))).getName()+" "+((Employee)(list.get(i))).getAge());
}
}

// Fuzzy query 
public List likeString(String likename){
for(int i=0;i<list.size();i++){
if(((Employee)(list.get(i))).getName().indexOf(likename)<=-1)
list.remove(i);
}
return list;

}

public static void main(String arg[]){
ListLike ll=new ListLike();
ll.addList("wuxiao",13);
ll.addList("wangwang",11);
ll.addList("wanghua",12);
ll.addList("xiaowang",13);
ll.addList("xiaoxiao",13);

ll.likeString("wang");
ll.ShowList();


}

}

Related articles: