Java method: Finding object in array list given a known attribute value

后端 未结 8 1325
名媛妹妹
名媛妹妹 2020-12-16 11:43

I have a couple of questions actually.

I have a class Dog with the following instance fields:

private int id;
private int id_mother;         


        
相关标签:
8条回答
  • 2020-12-16 12:14

    I solved this using java 8 lambdas

    int dogId = 2;
    
    return dogList.stream().filter(dog-> dogId == dog.getId()).collect(Collectors.toList()).get(0);
    
    0 讨论(0)
  • 2020-12-16 12:17

    Assuming that you've written an equals method for Dog correctly that compares based on the id of the Dog the easiest and simplest way to return an item in the list is as follows.

    if (dogList.contains(dog)) {
       return dogList.get(dogList.indexOf(dog));
    }
    

    That's less performance intensive that other approaches here. You don't need a loop at all in this case. Hope this helps.

    P.S You can use Apache Commons Lang to write a simple equals method for Dog as follows:

    @Override
    public boolean equals(Object obj) {     
       EqualsBuilder builder = new EqualsBuilder().append(this.getId(), obj.getId());               
       return builder.isEquals();
    }
    
    0 讨论(0)
提交回复
热议问题