1+ package com .amitph .java .collections .list ;
2+
3+ import com .google .common .collect .Sets ;
4+ import org .apache .commons .collections4 .CollectionUtils ;
5+
6+ import java .util .ArrayList ;
7+ import java .util .HashSet ;
8+ import java .util .List ;
9+ import java .util .Set ;
10+
11+ public class ListsDifferenceFinder {
12+
13+ private final List <String > one = List .of ("Ray" , "Tim" , "Leo" , "Bee" , "Tim" );
14+ private final List <String > two = List .of ("Ray" , "Mia" , "Lyn" , "Bee" , "Zoe" , "Mia" );
15+
16+ public void usingPlainJava () {
17+ System .out .println ("The first List minus the second List" );
18+ List <String > difference = new ArrayList <>(one );
19+ difference .removeAll (two );
20+
21+ System .out .println (difference );
22+
23+ System .out .println ("The second List minus the first List" );
24+ difference = new ArrayList <>(two );
25+ difference .removeAll (one );
26+
27+ System .out .println (difference );
28+ }
29+
30+ public void usingStreams () {
31+ System .out .println ("The first List minus the second List" );
32+ List <String > difference = one .stream ()
33+ .filter (e -> !two .contains (e ))
34+ .toList ();
35+ System .out .println (difference );
36+
37+ System .out .println ("The second List minus the first List" );
38+ difference = two .stream ()
39+ .filter (e -> !one .contains (e ))
40+ .toList ();
41+ System .out .println (difference );
42+ }
43+
44+ public void usingApacheCommons () {
45+ System .out .println ("The first List minus the second List" );
46+ List <String > differences = new ArrayList <>(CollectionUtils .removeAll (one , two ));
47+ System .out .println (differences );
48+
49+ System .out .println ("The second List minus the first List" );
50+ differences = new ArrayList <>((CollectionUtils .removeAll (two , one )));
51+ System .out .println (differences );
52+ }
53+
54+ public void usingGuava () {
55+ Set <String > differences = Sets .difference (new HashSet <>(two ), new HashSet <>(one ));
56+ System .out .println (differences );
57+ }
58+
59+
60+ public static void main (String [] a ) {
61+ ListsDifferenceFinder differenceFinder = new ListsDifferenceFinder ();
62+
63+ System .out .println ("Using Plain Java:" );
64+ differenceFinder .usingPlainJava ();
65+
66+ System .out .println ();
67+ System .out .println ("Using Java Streams:" );
68+ differenceFinder .usingStreams ();
69+
70+ System .out .println ();
71+ System .out .println ("Using Apache Commons Collection:" );
72+ differenceFinder .usingApacheCommons ();
73+
74+ System .out .println ();
75+ System .out .println ("Using Guava:" );
76+ differenceFinder .usingGuava ();
77+ }
78+ }
0 commit comments