一.需求
今天做的是将两个字符串转为数组后再转集合,然后利用集合的流stream来进行差集过滤
二.差集代码
差集:将两个集合相同的数据去掉,留下不同的数据
1 @Test
2 public void wzwcs()
3 {
4 // 字符串1
5 String strOne = "123,1234";
6 // 字符串2
7 String strTow = "123,1234,12345";
8 // 已逗号分隔转为数组1
9 String[] splitOne = strOne.split(",");
10 // 已逗号分隔转为数组2
11 String[] splitTow = strTow.split(",");
12 // 将数组转为集合1
13 List listOne = Arrays.asList(splitOne);
14 // 将数组转为集合2
15 List listTow = Arrays.asList(splitTow);
16 // 直接写集合流将 集合2 流化,过滤(集合2的各个值->集合1.非包含(集合2的各个值)).转为set集合
17 Set result = listTow.stream().filter(e->!listOne.contains(e)).collect(Collectors.toSet());
18 // 遍历差集
19 for (String s : result)
20 {
21 // 打印
22 System.out.println("result.toString() = " + s);
23 }
24 }
三.交集代码
交集:将相同的代码留下
交集代码其实就非包含变为包含
1 @Test
2 public void wzwcs()
3 {
4 // 字符串1
5 String strOne = "123,1234";
6 // 字符串2
7 String strTow = "123,1234,12345";
8 // 已逗号分隔转为数组1
9 String[] splitOne = strOne.split(",");
10 // 已逗号分隔转为数组2
11 String[] splitTow = strTow.split(",");
12 // 将数组转为集合1
13 List listOne = Arrays.asList(splitOne);
14 // 将数组转为集合2
15 List listTow = Arrays.asList(splitTow);
16 // 直接写集合流将 集合2 流化,过滤(集合2的各个值->集合1.包含(集合2的各个值)).转为set集合
17 Set result = listTow.stream().filter(e->listOne.contains(e)).collect(Collectors.toSet());
18 // 遍历交集
19 for (String s : result)
20 {
21 // 打印
22 System.out.println("result.toString() = " + s);
23 }
24 }