Lambda实现Java List的交集/并集/差集/去重复并集

经常记不住,只能写下来了!!!

  • 1.8之前交、并集采用简单的 removeAll retainAll 等操作
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
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {
List<String> list1 = new ArrayList();
list1.add("1111");
list1.add("2222");
list1.add("3333");

List<String> list2 = new ArrayList();
list2.add("3333");
list2.add("4444");
list2.add("5555");

// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
System.out.println("---得到交集 intersection---");
intersection.parallelStream().forEach(System.out :: println);

// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
System.out.println("---得到差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out :: println);

// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(toList());
System.out.println("---得到差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out :: println);

// 并集
List<String> listAll = list1.parallelStream().collect(toList());
List<String> listAll2 = list2.parallelStream().collect(toList());
listAll.addAll(listAll2);
System.out.println("---得到并集 listAll---");
listAll.parallelStream().forEach(System.out :: println);

// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(toList());
System.out.println("---得到去重并集 listAllDistinct---");
listAllDistinct.parallelStream().forEach(System.out :: println);

System.out.println("---原来的List1---");
list1.parallelStream().forEach(System.out :: println);
System.out.println("---原来的List2---");
list2.parallelStream().forEach(System.out :: println);

// 一般有filter 操作时,不用并行流parallelStream ,如果用的话可能会导致线程安全问题
}
}

Stream流之List、Integer[]、int[]相互转化

  • int[ ] 转 Integer[ ]
1
Integer[] integers = Arrays.stream(arr).boxed().toArray(Integer[]::new);
  • int[ ] 转 List< Integer >

    1
    2
    3
    4
    5
    public static void main(String[] args) {
    int[] arr = { 1, 2, 3, 4, 5 };
    List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
    list.forEach(e -> System.out.print(e + " "));
    }
  • Integer[ ]转 int[ ]

    1
    int[] arr= Arrays.stream(integers).mapToInt(Integer::valueOf).toArray();
  • Integer[ ]转 List< Integer >

    1
    2
    Integer[] integers = {1,2,3,4,5};
    List<Integer> list = Arrays.asList(integers);
  • List< Integer > 转 Integer[ ]

    1
    Integer[] integers = list.toArray(new Integer[list.size()]);
  • List< Integer > 转 int[ ]

    1
    int[] arr2 = list.stream().mapToInt(Integer::valueOf).toArray();