Java8之根据指定情况过滤
一、背景
在用java8开发的时候,存在一些场景,如查询时,根据入参中的某个字段,如果不为空,则根据该字段进行过滤。
原代码类似:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
class People
{
private String name;
private String city;
private int age;
}
class SearchRequest
{
private String namePrefix;
private String city;
}
// 某个过滤方法
private static List<People> filterDemo1(SearchRequest request)
{
if (request == null)
{
return Lists.newArrayList();
}
List<People> peopleList = Lists.newArrayList();
peopleList.add(new People("张三", "北京", 20));
peopleList.add(new People("张四", "上海", 30));
peopleList.add(new People("王五", "广州", 40));
peopleList.add(new People("小明", "深圳", 50));
List<People> filterByNameList = Lists.newArrayList();
if (StringUtils.isNotEmpty(request.getNamePrefix()))
{
filterByNameList = peopleList.stream()
.filter(p -> StringUtils.startsWith(p.getName(), request.getNamePrefix()))
.collect(Collectors.toList());
}
else
{
filterByNameList = peopleList;
}
List<People> filterByCityList = Lists.newArrayList();
if (StringUtils.isNotEmpty(request.getCity()))
{
filterByCityList = filterByNameList.stream()
.filter(p -> StringUtils.equalsIgnoreCase(p.getName(), request.getCity()))
.collect(Collectors.toList());
}
else
{
filterByCityList = filterByNameList;
}
return filterByCityList;
}
二、优雅实现
利用或运算短路运算符实现1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19private static List<People> filterDemo2(SearchRequest request)
{
if (request == null)
{
return Lists.newArrayList();
}
List<People> peopleList = Lists.newArrayList();
peopleList.add(new People("张三", "北京", 20));
peopleList.add(new People("张四", "上海", 30));
peopleList.add(new People("王五", "广州", 40));
peopleList.add(new People("小明", "深圳", 50));
boolean needFilterByName = StringUtils.isNotEmpty(request.getNamePrefix());
boolean needFilterByCity = StringUtils.isNotEmpty(request.getCity());
return peopleList.stream()
.filter(p -> !needFilterByName || StringUtils.startsWith(p.getName(), request.getNamePrefix()))
.filter(p -> !needFilterByCity || StringUtils.equalsIgnoreCase(p.getName(), request.getCity()))
.collect(Collectors.toList());
}