1+ package com .amitph .java .collections .list ;
2+
3+ import org .apache .commons .collections4 .CollectionUtils ;
4+
5+ import java .util .ArrayList ;
6+ import java .util .List ;
7+ import java .util .function .Predicate ;
8+
9+ public class ListsComparer {
10+ public void checkEquality () {
11+ List <Integer > one = List .of (1 , 2 , 4 , 6 , 8 );
12+ List <Integer > two = List .of (1 , 2 , 4 , 6 , 8 );
13+ List <Integer > three = List .of (1 , 2 , 4 , 6 , 8 , 4 );
14+
15+ System .out .println (one .equals (two ));
16+ System .out .println (one .equals (three ));
17+ }
18+
19+ public void findCommonElements () {
20+ List <Integer > one = List .of (1 , 2 , 4 , 6 , 8 );
21+ List <Integer > two = List .of (3 , 4 , 5 , 6 , 7 );
22+
23+ //Plain Java
24+ List <Integer > commons = new ArrayList <>(one );
25+ commons .retainAll (two );
26+ System .out .println (commons );
27+
28+ //Java Streams
29+ commons = one .stream ()
30+ .filter (two ::contains )
31+ .toList ();
32+ System .out .println (commons );
33+
34+ //Apache Commons Collections
35+ commons = new ArrayList <>(CollectionUtils .intersection (one , two ));
36+ System .out .println (commons );
37+ }
38+
39+ public void findDifferentElements () {
40+ List <Integer > one = List .of (1 , 2 , 4 , 6 , 8 );
41+ List <Integer > two = List .of (3 , 4 , 5 , 6 , 7 );
42+
43+ //Plain Java
44+ List <Integer > difference = new ArrayList <>(one );
45+ difference .removeAll (two );
46+ System .out .println (difference );
47+
48+ //Java Streams
49+ difference = one .stream ()
50+ .filter (Predicate .not (two ::contains ))
51+ .toList ();
52+ System .out .println (difference );
53+
54+ //Apache Commons Collections
55+ difference = new ArrayList <>(CollectionUtils .removeAll (one , two ));
56+ System .out .println (difference );
57+ }
58+
59+ public static void main (String [] a ) {
60+ ListsComparer comparer = new ListsComparer ();
61+ comparer .checkEquality ();
62+ comparer .findCommonElements ();
63+ comparer .findDifferentElements ();
64+ }
65+ }
0 commit comments