模糊查询String类型的List
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对象集合进行模糊查找
使用下面的工具类
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 ;
public class FilterUtil {
public static < T > List < T > listFilter ( List < T > list, String target, Function < T , ? > function) {
List < T > result = null ;
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 ( ) ) ;
}
}