Java List.contains(Object with field value equal t

2019-01-03 12:02发布

I want to check whether a List contains an object that has a field with a certain value. Now, I could use a loop to go through and check, but I was curious if there was anything more code efficient.

Something like;

if(list.contains(new Object().setName("John"))){
    //Do some stuff
}

I know the above code doesn't do anything, it's just to demonstrate roughly what I am trying to achieve.

Also, just to clarify, the reason I don't want to use a simple loop is because this code will currently go inside a loop that is inside a loop which is inside a loop. For readability I don't want to keep adding loops to these loops. So I wondered if there were any simple(ish) alternatives.

13条回答
来,给爷笑一个
2楼-- · 2019-01-03 12:59

Google Guava

If you're using Guava, you can take a functional approach and do the following

FluentIterable.from(list).find(new Predicate<MyObject>() {
   public boolean apply(MyObject input) {
      return "John".equals(input.getName());
   }
}).Any();

which looks a little verbose. However the predicate is an object and you can provide different variants for different searches. Note how the library itself separates the iteration of the collection and the function you wish to apply. You don't have to override equals() for a particular behaviour.

As noted below, the java.util.Stream framework built into Java 8 and later provides something similar.

查看更多
登录 后发表回答