赞
踩
List<String> list = new ArrayList<>();
list.add("test");
list.add("testA");
list.add("fall");
List<String> result = list.stream().filter(item->item.contains("te")).collect(Collectors.toList());
System.out.println(result.toString());
// 通过姓名模糊查找
list = FilterUtil.listFilter(
// 待筛选数据集合
list,
// 姓名
name,
User::getName);
import java.util.*;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
/**
* @description:
* @author: evildoer
* @datetime: 2021/3/2 11:31
*/
public class FilterUtil{
/**
* @description: 模糊查找
* @param list 数据集合
* @param target 筛选目标
* @param function 函数
* @return: java.util.List<T>
* @author: evildoer
* @datetime: 2021/3/2 11:32
*/
public static <T> List<T> listFilter(List<T> list, String target, Function<T, ?> function) {
List<T> result = null;
// 判断target是否为空,空则不执行
if (StringUtils.isNotEmpty(target)) {
result = listFilter(list, target, function);
}
// 不满足条件直接返回原数据集合
return Optional.ofNullable(result).orElse(list);
}
public static <T> List<T> listFilter(List<T> list, String target, Function<T, ?> function) {
List<T> result = new LinkedList<>();
//该处决定大小写是否敏感
Pattern pattern = Pattern.compile(target, Pattern.CASE_INSENSITIVE);
for (T t : list) {
Matcher matcher = pattern.matcher(function.apply(t).toString());
if (matcher.find()) {
result.add(t);
}
}
return result;
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
@Data
@AllArgsConstructor
class User{
private String name;
private Integer age;
}
public class Test {
public static void main(String[] args) {
// 通过用户姓名模糊查找
String name = "张";
List<User> list = new ArrayList<>();
list.add(new User("张三", 18));
list.add(new User("张叁", 18));
list.add(new User("张山", 18));
list.add(new User("李四", 19));
list.add(new User("王五", 20));
list = FilterUtil.listFilter(
list,
name,
User::getName);
System.out.println(list.toString());
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。