当前位置: 代码迷 >> J2SE >> 怎么在List中进行模糊查询呢
  详细解决方案

怎么在List中进行模糊查询呢

热度:299   发布时间:2016-04-24 17:18:55.0
如何在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);
------解决方案--------------------
刚才我试了,输入wang查寻不到,wangqiang可以,这个是模糊查询吗?
------解决方案--------------------
学习
------解决方案--------------------
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();


}

}
  相关解决方案