在java List中停止模糊查詢的完成辦法。本站提示廣大學習愛好者:(在java List中停止模糊查詢的完成辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是在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()即可以停止模糊婚配
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中停止模糊查詢的完成辦法全部內容了,希望大家多多支持~