最近写个微信小程序,需要自己根据多个条件,去List中的对象属性去匹配和检索,因为之前实现都是去查询数据库,多条件直接拼,但是小程序这里不好使,因为不能使用数据库,所以简单的一个多条件查询也要自己实现(暂时没有想到更好的方案),贴出现有实现方案:
public class Test {
public static void main(String[] args) {
// 条件
String number = "";
String city = "天津";
String sex = "123";
String time = "";
ArrayList<Item> datas = new ArrayList<>();
datas.add(new Item("220", "北京", "12", "123"));
datas.add(new Item("220", "上海", "123", "123"));
datas.add(new Item("110", "广州", "13", "123"));
datas.add(new Item("35", "上海", "14", "234"));
datas.add(new Item("250", "上海", "", "123"));
datas.add(new Item("220", "北京", "123", "2345"));
ArrayList<Item> numberItem = new ArrayList<>();
if (number != "") {
for (int i = 0; i < datas.size(); i++) {
if (datas.get(i).number.equals(number)) {
numberItem.add(datas.get(i));
}
}
} else {
// 数据不变
numberItem .addAll (datas);
}
ArrayList<Item> cityItem = new ArrayList<>();
if (city != "") {
if (numberItem != null) {
for (int i = 0; i < numberItem.size(); i++) {
if (numberItem.get(i).city.equals(city)) {
cityItem.add(numberItem.get(i));
}
}
}
} else {
cityItem.addAll(numberItem) ;
}
ArrayList<Item> sextems = new ArrayList<>();
if (sex != "") {
if (cityItem != null) {
for (int i = 0; i < cityItem.size(); i++) {
if (cityItem.get(i).sex.equals(sex)) {
sextems.add(cityItem.get(i));
}
}
}
} else {
sextems.addAll(cityItem);
}
ArrayList<Item> timeItems = new ArrayList<>();
if (time != "") {
if (sextems != null) {
for (int i = 0; i < sextems.size(); i++) {
if (sextems.get(i).time.equals(time)) {
timeItems.add(sextems.get(i));
}
}
}
} else {
timeItems.addAll( sextems);
}
for (int i = 0; i < timeItems.size(); i++) {
System.out.println(timeItems.get(i).toString());
}
}
}
item.java如下所示
public class Item {
public String number;
public String city;
public String sex;
public String time;
public Item(String number, String city, String sex, String time) {
super();
this.number = number;
this.city = city;
this.sex = sex;
this.time = time;
}
@Override
public String toString() {
return "Item [number=" + number + ", city=" + city + ", sex=" + sex + ", time=" + time + "]";
}
}