ArrayList not using the overridden equals

后端 未结 11 1407
误落风尘
误落风尘 2021-02-08 14:13

I\'m having a problem with getting an ArrayList to correctly use an overriden equals. the problem is that I\'m trying to use the equals to only test for a single key field, and

11条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-08 14:47

    This post was first written before Java 8 was available but now that it's 2017 instead of using the List.containts(...) method you can use the new Java 8 way like this:

    System.out.println(objectList.stream().filter(obj -> obj.getTestKey().equals("UNIQUE ID1")).findAny().isPresent());
    

    And give your TestClass a getter for your testKey field:

    public String getTestKey() {
    
       return testKey;
    }
    

    The benefit of this approach is that you don't have to modify the equals or hash method and you'll look like a boss to your peers!

提交回复
热议问题