Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find object in ArrayList

Tags:

java

java-6

I want to find a LegalEntity object in an ArrayList. The object can possibly be a different instance. I'm only interested in whether they represent the same value, i.e. they have the same primary key. All LegalEntity instances are created from database values by EJB:

List<LegalEntity> allLegalEntities = myEJB.getLegalEntityfindAll());
LegalEntity currentLegalEntity = myEJB.getLegalEntityfindById(123L);

My first naive idea never finds matches:

if (allLegalEntities.contains(currentLegalEntity)) {
}

I then thought that perhaps I need to create my own equals() method:

public boolean equals(LegalEntity other) {
    return legalEntityId.equals(other.legalEntityId);
}

But this method is not even being invoked. Is there a way to find an object in a list that doesn't involve looping?

I'm learning Java so it might easily be some foolish misunderstanding on my side.

like image 994
Álvaro González Avatar asked May 11 '26 16:05

Álvaro González


2 Answers

Your approach is correct, but you need to override the method equals that accepts an Object:

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    LegalEntity other = (LegalEntity) obj;
    // check if equals based one some properties
}

However you also need to override hashCode:

@Override
public int hashCode() {
    // return a unique int
}

So this might not be the easiest solution.

Another approach is to use filter:

LegalEntity myLegalEntity = myEJB.getLegalEntityfindAll().stream()
                              .filter(legalEntity -> legalEntity.getProperty().equals("someting"))
                              .findAny()
                              .orElse(null);

More info here

like image 96
Marc Avatar answered May 14 '26 08:05

Marc


If you're using Java 8 you can use streams:

List<LegalEntity> allLegalEntities = myEJB.getLegalEntityfindAll());
LegalEntity currentLegalEntity = allLegalEntities.stream().filter(entity -> entity.getId() == 123L).findFirst();
like image 45
Joakim Rönning Avatar answered May 14 '26 06:05

Joakim Rönning



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!