1

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
 }
 }
Idos
15.3k14 gold badges63 silver badges81 bronze badges
asked Mar 16, 2016 at 15:21
1
  • If your list is sorted, then you can use Collections.binarySearch Commented Mar 16, 2016 at 15:32

2 Answers 2

2

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;)

answered Mar 16, 2016 at 15:26
Sign up to request clarification or add additional context in comments.

Comments

0

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.

answered Mar 16, 2016 at 15:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.