Search code examples
javalistsearchcontains

Java List.contains(ArrayList<String> with field value equal to x)


Using the code below I am able to check if a List of Objects contains field matching specific value.

public boolean containsName(final List<MyObject> list, final String name){
    return list.stream().filter(o -> o.getName().equals(name)).findFirst().isPresent();
}

However, this works only when o.getName() returns a String. I am trying to modify the code so this works when MyObject contains an ArrayList<String> and name can match any element in the list. Something like this:

public boolean containsKeyword(final List<KeywordPOJO> list, final String keyword){
    return list.stream().filter(o -> o.getKeywordList().equals(keyword)).findFirst().isPresent();
}

Where KeywordPOJO returns a list of keywords instead of a single String. If keyword matches ANY of those keywords method should return true.

At the present moment, Eclipse throws warnings: Unlikely argument type for equals(): String seems to be unrelated to ArrayList<String> (because keyword is a String and getKeywordList() returns ArrayList<String>)

Thanks!


Solution

  • You can simply use List.contains:

    o -> o.getKeywordList().contains(keyword);
    

    As a side note, your expression could be simplified with Stream.anyMatch:

    public boolean containsKeyword(final List<KeywordPOJO> list, final String keyword){
        return list.stream().anyMatch(o -> o.getKeywordList().contains(keyword));
    }