0

I do have a simple Object which can be identified by a String. These identifiers are unique.

public class SomeObject 
{

    private String identifier;

    public String getIdentifier() {
        return this.identifier;
    }
}

I now have another class which holds a List of these simple Objects and has a method to return the object that matches the identifier provided if it exists in the list.

public class SomeBiggerClass
{

    LinkedList<SomeObject> allObjects;

    public SomeObject getObject(String identifier)
    {
        if (this.allObjects.stream().anyMatch(object -> object.getIdentifier() == identifier)) {
            return this.allObjects.stream().filter(object -> object.getIdentifier() == identifier).findAny().get();
        }
        else {
            return null;
        }
    }
}

However even if the Strings exactly match it will return false for the anyMatch() part and will throw an exception for the second lambda. I would be alble to do this in c# and linq, however I'm kinda lost with these java lambdas. Any ideas on how to do this would be apreciated.

davidf
  • 170
  • 1
  • 1
  • 9

1 Answers1

1

You need to use .equals(...) instead of == in order to compare strings.

Nicola Ferraro
  • 4,051
  • 5
  • 28
  • 60