For example, I have a List like below, which stores multiple Employee objects. Then I want to do a fuzzy query on this List according to the name of the Employee object. Is there any good solution?
For example, if the query condition I entered is "wang", then the List list containing only employee1 should be returned.
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 above one is case sensitive. If the case insensitive is required, change it to:
Pattern pattern = Pattern.compile(name,Pattern.CASE_INSENSITIVE);
And the above is an exact query. If you want to fuzzy match, matcher.find() can perform fuzzy matches.
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();//Add employees 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();}}The above is all the content of the implementation method of fuzzy query in Java List brought to you by the editor. I hope everyone will support Wulin.com more~