1+ package org .hisp .dhis .util ;
2+
3+ import java .util .Collection ;
4+ import java .util .HashMap ;
5+ import java .util .Map ;
6+
7+ /**
8+ * Duplicate value finder.
9+ */
10+ public class DuplicateFinder {
11+
12+ private Map <String , Integer > valueCounts ;
13+
14+ /**
15+ * Constructor.
16+ */
17+ public DuplicateFinder () {
18+ this .valueCounts = new HashMap <>();
19+ }
20+
21+ /**
22+ * Constructor.
23+ *
24+ * @param values the collection of values.
25+ */
26+ public DuplicateFinder (Collection <String > values ) {
27+ this ();
28+ addAll (values );
29+ }
30+
31+ /**
32+ * Adds a value.
33+ *
34+ * @param value the value.
35+ */
36+ public void add (String value ) {
37+ valueCounts .put (value , valueCounts .getOrDefault (value , 0 ) + 1 );
38+ }
39+
40+ /**
41+ * Adds a collection of values.
42+ *
43+ * @param values the values.
44+ */
45+ public void addAll (Collection <String > values ) {
46+ values .forEach (value -> add (value ));
47+ }
48+
49+ /**
50+ * Returns the duplicates as a map, where the key is the duplicate value and the value is the
51+ * number of occurrences.
52+ *
53+ * @return the duplicates as a map.
54+ */
55+ public Map <String , Integer > getDuplicates () {
56+ Map <String , Integer > duplicates = new HashMap <>();
57+ for (Map .Entry <String , Integer > entry : valueCounts .entrySet ()) {
58+ if (entry .getValue () > 1 ) {
59+ duplicates .put (entry .getKey (), entry .getValue ());
60+ }
61+ }
62+ return duplicates ;
63+ }
64+ }
0 commit comments