CodeMonkey
CodeMonkey

Reputation: 2285

Looping over a list in Java to check for a value

I have a list of an object

List<myObj> myObjList

Here, myObj is a class with the following structure:

public class myObj {
    private String id;
    private String pwd;
    private String type;
    //Getters/Setters
}

I want to loop through the list to check, if i have a particular id. I tried :

for (obj : myObjList) {
    if (MY_STRING.equals(obj.getId())) {
        aBooleanFlag = true;
    }
}

However, when i want to use, contains method, it is failing. The way i am using it is :

if(myObj.contains(MY_STRING)) {
    aBooleanFlag = true;    
}           

Can you suggest what is wrong and how to fix it

Upvotes: 1

Views: 124

Answers (5)

user207421
user207421

Reputation: 310840

You should be using a Map instead of a List.

Upvotes: -2

David Conrad
David Conrad

Reputation: 16359

You are comparing a String to an entire MyObj object using equals. This is like asking whether your car is equal to a hubcap (one part of your car).

You can either iterate over the list:

boolean found = false;
for (MyObj obj : myObjList) {
    if (obj.getId().equals(MY_STRING)) {
        found = true;
        break;
    }
}

Or you can use Java 8 streams with anyMatch() and a predicate:

boolean found = myObjList.stream().anyMatch(obj -> obj.getId().equals(MY_STRING));

Or you can use a Map instead of a List, and look items up by id:

Map<String, MyObj> theMap = new HashMap<>();
// put MyObj's into the map by id
theMap.put(myObj.getId(), myObj);
// check for one using its id
boolean found = theMap.containsKey(MY_STRING);

I changed the name of the class from myObj to MyObj because the convention is that class names start with capital letters in Java.

Upvotes: 0

Chris Witteveen
Chris Witteveen

Reputation: 495

In your loop you use .equals(Object).
If you want to compare 2 String you should use .equalsIgnoreCase(String).
You als neeed to define what obj is.
So this would be your code:

for (Object obj : myObjList) {
    if (MY_STRING.equalsIgnoreCase(obj.getId())) {
        aBooleanFlag = true;
    }
}

If you use the if method, you should check if the List contains the String.
Checking if a class contains a String would not help.
So your code there would be:

if(myObjList.contains(MY_STRING)) {
    aBooleanFlag = true;    
} 

Hope it helped

Upvotes: 0

JHDev
JHDev

Reputation: 995

Change

if(myObj.contains(MY_STRING)) {
    aBooleanFlag = true;    
}  

to

if (myObj.getId().contains(MY_STRING)) {
        aBooleanFlag = true;
    }

Upvotes: 0

SLaks
SLaks

Reputation: 887215

.contains() checks whether any object in the list is equal to the parameter.

A myObj instance will never equal a String.

Upvotes: 3

Related Questions