匹配集合最后一个满足条件的元素 CollUtil.lastIndexOf()
List<String> list = CollUtil.newArrayList("AngelaBaby", "Baby", "smallBaby");
int baby2 = CollUtil.lastIndexOf(list, s -> s.contains("Baby"));
System.out.println("baby = " + baby);
baby2 = 2
自己定义是否满足写法
List<String> list = CollUtil.newArrayList("AngelaBaby", "Baby", "smallBaby");
int baby = CollUtil.lastIndexOf(list, new Matcher<String>() {
@Override
public boolean match(String s) {
return s.contains("Baby");
}
});
System.out.println("baby = " + baby);
baby = 2
Matcher 用法
List<Person> personList = new ArrayList<>();
personList.add(new Person("12", "洛欣", 26));
personList.add(new Person("13", "祺欣", 24));
personList.add(new Person("14", "小康", 28));
personList.add(new Person("15", "明鹏", 25));
personList.add(new Person("16", "小轩轩", 22));
personList.add(new Person("17", "宇明", 27));
int index = CollUtil.indexOf(personList, p -> StrUtil.startWith(p.getName(), "小"));
System.out.println("index = " + index);
Matcher<Person> matcher = new Matcher<Person>() {
@Override
public boolean match(Person person) {
String name = person.getName();
if (name.length() >= 3 && StrUtil.startWith(name, "小")) {
return true;
}
return false;
}
};
int index2 = CollUtil.indexOf(personList, matcher);
System.out.println("index2 = " + index2);
index = 2
index2 = 4
依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.7.15</version>
</dependency>
|