@Data
class Person {
private String name;
private Integer age;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name.equals(person.name) && age.equals(person.age);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
}
@RequestMapping(value = "test6")
public void test6(HttpServletResponse rsp) {
//普通业务集合
List<Person> personList = new ArrayList<>();
personList.add(new Person("小D", 26));
personList.add(new Person("佳欣", 24));
personList.add(new Person("铭康", 28));
personList.add(new Person("小鹏", 25));
personList.add(new Person("宇轩", 22));
personList.add(new Person("小明", 27));
//条件
Predicate<Person> predicate = person -> person.getAge() > 22 && StrUtil.contains(person.getName(), "小");
//以下条件等价于上面条件
Predicate<Person> predicate1 = person -> person.getAge() > 22;
Predicate<Person> predicate2 = person -> StrUtil.contains(person.getName(), "小");
Map<Integer, Person> result = new HashMap<>();
for (int i = 0; i < personList.size(); i++) {
Person person = personList.get(i);
if (predicate.test(person)) {
result.put(i, person);
}
//以下不同写法,对于条件特别多用下面这种
// if (predicate1.and(predicate2).test(person)) {
// result.put(i, person);
// }
}
System.out.println(result);
return;
}
结果
{0=TestController.Person(name=小D, age=26), 3=TestController.Person(name=小鹏, age=25), 5=TestController.Person(name=小明, age=27)}