Niklas
Niklas

Reputation: 64

Best way to check array elements contain specific value

I have a list of objects and have to search through this list if it contains a specific value. The specific values are all saved in an array. What should I set for allValuesFromArray in the code below so that it would function accordingly?

List<ownClass> objectList;
String[] specificValueArray = {"value0","value1","value2","value3"};
for (ownClass object:objectlist){
    if (object.getSomeValue() == allValuesFromArray){
            //some code
        }
    }

Upvotes: 1

Views: 55

Answers (2)

Darth Android
Darth Android

Reputation: 3502

Have you tried:

if (!objectList.retainAll(Arrays.asList(specificValueArray)).isEmpty()) {
    //some code
}

This disguises the complexity a bit, in that this is O(n^2), but is clean and readable.

Upvotes: 0

Idos
Idos

Reputation: 15310

IIUC, you can use:

if (Arrays.asList(specificValueArray).contains(object.getSomeValue())){
    ...
}

This will return true if object.getSomeValue() is inside specificValueArray (remember to
import java.util.Arrays;)

Upvotes: 2

Related Questions