如何在java List中进行模糊查询
比如我有下面这样一个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()即可以进行模糊匹配
上面那个是大小写敏感的,如果要求大小写不敏感,改成:
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; }