在java List中进行模糊查询的实现方法
程序员文章站
2024-03-11 13:03:55
比如我有下面这样一个list,里面存放的是多个employee对象。然后我想对这个list进行按照employee对象的名字进行模糊查询。有什么好的解决方案么?
比如我输...
比如我有下面这样一个list,里面存放的是多个employee对象。然后我想对这个list进行按照employee对象的名字进行模糊查询。有什么好的解决方案么?
比如我输入的查询条件为“wang”,那么应该返回只包含employee1的list列表。
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);
方式一:
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; }
上面那个是大小写敏感的,如果要求大小写不敏感,改成:
pattern pattern = pattern.compile(name,pattern.case_insensitive);
并且上面那个是精确查询,如果要模糊匹配,matcher.find()即可以进行模糊匹配
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; }
方式二:
public class listlike { //定义员工类 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(); //增加员工 public list addlist(string name,int age){ employee employee1 = new employee(); employee1.setname(name); employee1.setage(age); list.add(employee1); return list; } //显示所有员工 public void showlist(){ for(int i=0;i<list.size();i++){ system.out.println(((employee)(list.get(i))).getname()+" "+((employee)(list.get(i))).getage()); } } //模糊查询 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(); } }
以上就是小编为大家带来的在java list中进行模糊查询的实现方法全部内容了,希望大家多多支持~