|
@@ -1,7 +1,63 @@
|
1
|
1
|
package com.zipcodewilmington.arrayutility;
|
2
|
2
|
|
|
3
|
+import java.util.Arrays;
|
|
4
|
+import java.util.Map;
|
|
5
|
+import java.util.stream.Collectors;
|
|
6
|
+
|
|
7
|
+import static java.util.stream.Collectors.counting;
|
|
8
|
+
|
3
|
9
|
/**
|
4
|
10
|
* Created by leon on 3/6/18.
|
5
|
11
|
*/
|
6
|
|
-public class ArrayUtility {
|
|
12
|
+public class ArrayUtility <T> {
|
|
13
|
+ private T[] initialArray;
|
|
14
|
+
|
|
15
|
+ public ArrayUtility(T[] initialArray) {
|
|
16
|
+ this.initialArray = initialArray;
|
|
17
|
+ }
|
|
18
|
+
|
|
19
|
+ private T[] combineArray(T[] merge) {
|
|
20
|
+ T[] mergedArray = Arrays.copyOf(merge, merge.length + this.initialArray.length);
|
|
21
|
+ for (int i = 0; i < mergedArray.length; i++) {
|
|
22
|
+ mergedArray[i] = i >= initialArray.length
|
|
23
|
+ ? merge[i - initialArray.length]
|
|
24
|
+ : initialArray[i];
|
|
25
|
+ }
|
|
26
|
+ return mergedArray;
|
|
27
|
+ }
|
|
28
|
+
|
|
29
|
+ public int countDuplicatesInMerge(T[] elements, T value) {
|
|
30
|
+ return (int) Arrays.stream(combineArray(elements))
|
|
31
|
+ .filter(e -> e == value)
|
|
32
|
+ .count();
|
|
33
|
+ }
|
|
34
|
+
|
|
35
|
+ public T getMostCommonFromMerge(T[] elements) {
|
|
36
|
+ return Arrays.stream(combineArray(elements))
|
|
37
|
+ .collect(Collectors.groupingBy(x -> x, counting()))
|
|
38
|
+ .entrySet()
|
|
39
|
+ .stream()
|
|
40
|
+ .max(Map.Entry.comparingByValue())
|
|
41
|
+ .get()
|
|
42
|
+ .getKey();
|
|
43
|
+ }
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+ public Integer getNumberOfOccurrences (T value) {
|
|
47
|
+ return (int) (long) Arrays.stream(this.initialArray)
|
|
48
|
+ .collect(Collectors.groupingBy(x -> x, counting()))
|
|
49
|
+ .entrySet()
|
|
50
|
+ .stream()
|
|
51
|
+ .filter(e -> e.getKey().equals(value))
|
|
52
|
+ .map(Map.Entry::getValue)
|
|
53
|
+ .findFirst()
|
|
54
|
+ .orElse(null);
|
|
55
|
+ }
|
|
56
|
+
|
|
57
|
+ public T[] removeValue(T value) {
|
|
58
|
+ return Arrays.stream(this.initialArray)
|
|
59
|
+ .filter(x -> x != value)
|
|
60
|
+ .collect(Collectors.toList())
|
|
61
|
+ .toArray(Arrays.copyOf(this.initialArray, 0));
|
|
62
|
+ }
|
7
|
63
|
}
|