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