复杂的过滤
#
1import com.google.common.collect.Lists;
2import lombok.AllArgsConstructor;
3import lombok.Data;
4import org.apache.commons.lang3.StringUtils;
5
6import java.util.List;
7import java.util.stream.Collectors;
8
9public class FilterTest {
10
11 public static void testData() {
12 List<Record> recordsA = Lists.newArrayList(
13 new Record("A", "a1"),
14 new Record("A", "a2"),
15 new Record("A", "a4"),
16 new Record("A", "a5"),
17 new Record("B", "b1"),
18 new Record("B", "b2"),
19 new Record("B", "b7"),
20 new Record("D", "b7")
21 );
22 List<Record> recordsB = Lists.newArrayList(
23 new Record("A", "a1"),
24 new Record("A", "a2"),
25 new Record("A", "a3"),
26 new Record("B", "b1"),
27 new Record("B", "b2"),
28 new Record("B", "b3"),
29 new Record("B", "a1"),
30 new Record("C", "c1"),
31 new Record("C", "c2"),
32 new Record("C", "b1")
33 );
34
35 // 查找出新增的
36 List<Record> addRecordsA = recordsB.stream().filter(n -> recordsA.stream().noneMatch(o -> StringUtils.equals(o.getCate(), n.getCate()))).collect(Collectors.toList());
37 List<Record> addRecordsB = recordsB.stream().filter(n -> recordsA.stream().filter(o -> StringUtils.equals(o.getCate(), n.getCate())).noneMatch(o -> StringUtils.equals(o.getProd(), n.getProd()))).collect(Collectors.toList());
38 List<Record> addRecordsC = recordsB.stream().filter(n -> recordsA.stream().noneMatch(o -> StringUtils.equals(o.getProd(), n.getProd()))).collect(Collectors.toList());
39 System.out.println(addRecordsA);
40 System.out.println(addRecordsB); // 只有这个符合要求
41 System.out.println(addRecordsC);
42
43 // 查找删除的
44 List<Record> deleteRecordsB = recordsA.stream().filter(n -> recordsB.stream().filter(o -> StringUtils.equals(o.getCate(), n.getCate())).noneMatch(o -> StringUtils.equals(o.getProd(), n.getProd()))).collect(Collectors.toList());
45 System.out.println(deleteRecordsB);
46 }
47
48 @Data
49 @AllArgsConstructor
50 public static class Record {
51 private String cate;
52 private String prod;
53 }
54}