user2723295 user2723295 - 4 days ago 5
Java Question

Attempting to compare two arrays with Arrays.contains Java

I am trying to see if an element in my array is contained in one of my other arrays. I don't want to use a nested for loop for this and I am curious as to why my

.contains
does not work.

Currently I have two arrays

double [] s2 = new double [4];
double [] match = new double [s2.length];


and I am trying to test if
s2
contains any of the values in my
match
array

for (j = 0; j < s2.length; j++)
{
if(Arrays.asList(s2).contains(match[j])){
return true;
}
}


Does this have something to do with the double datatype I am using? If so is there a way I can still use
.contains
?

Answer

Addressing the specific problem: Arrays.asList does not create a List of your elements but a List of only one value: your double[] of elements (at index 0). You should iterate through the list yourself for a second for loop instead of creating a different object.


It can be done with Stream operations () instead of using loops, although the difference should be minimal.

DoubleStream.of(s2)      // Pipe the source array
    .distinct()          // Remove duplicate elements
                         // as they only need to be matched against once
    .anyMatch(value ->   // Consider if any value matches this condition
        IntStream.of(match)  // It equals any value in "match"
                 .distinct() // after removing duplicate elements
                 .anyMatch(matchValue -> matchValue == value));
Comments