Hi may someone suggest the fastest way to compare 2 arrays in java returning a string of an intersection array or a 'nil' value if there are no matches
static int [] WinnerNumbers; static int [] ClientNumbers;
After executing my program, I end up with 2 filled arrays (WinnerNumbers and ClientNumbers) of which I need to compare and return a match or null.
I would like to do this via a function
public static String WinnerChecker(){
prize = (......)
return prize;
}
I'd do it like this. It returns an empty String if no intersection (which is what I presumed you meant by nil
).
int[] a = { 1, 2, 4, 3 ,5, 9};
int[] b = { 4, 5, 6, 7, 8, 9, 11, 12, 13 };
String intersection = getIntersection(a, b);
System.out.println(intersection);
public static String getIntersection(int[] a, int[] b) {
return Arrays.stream(a)
.flatMap(i -> Arrays.stream(b).filter(k -> i == k))
.mapToObj(String::valueOf)
.collect(Collectors.joining(""));
}
Prints
459
If there are duplicates in either array and they are not wanted in the output, then add the method .distinct()
right before the mapToObj
process.
If one wants to return the result as an array, the following works.
public static int[] getIntersection(int[] a, int[] b) {
return Arrays.stream(a)
.flatMap(i -> Arrays.stream(b).filter(k -> i == k))
.toArray();
}
Another way which may be more efficient than those above is using sets.
public static String getIntersection(int[] a, int[] b) {
Set<Integer> seta =
Arrays.stream(a).boxed().collect(Collectors.toSet());
Set<Integer> setb =
Arrays.stream(b).boxed().collect(Collectors.toSet());
seta.retainAll(setb);
return seta.stream().map(String::valueOf)
.collect(Collectors.joining(""));
}
The actual set could be returned instead if that is desired.