'What’s the best way to check if a list contains an item other than specified item?

Lets say I have a list and I want to search for an item with value “apple”.

List<String> items = new Arraylist<>():

I want to return false if items contains at least one element other than the item mentioned (“apple”), true if all items in the list are “apples”.



Solution 1:[1]

Here's a one-liner:

return items.stream().anyMatch(s -> !s.equals("apple"));

or cute but a little less obvious:

return items.stream().allMatch("apple"::equals);

Solution 2:[2]

I use python but, I think is something like that:

list_entrance = input()

new_list = []

for cycle in list_entrance: if cycle != "apple": print("falce") else: continue

If you want of course you can "append" a items in "new_list". I don't know full condition on your task.

Solution 3:[3]

Just to say your ArrayList should be defined like this:

List items = new ArrayList<>();

You missed out some caps in the question.

For the solution you could just loop through the list and check:

for (int x = 0; x<items.size(); x++){
    if (! items.get(x).equals("apple")){
        return false;
    } 
}
return true;

Solution 4:[4]

Instead use a Set, in order not to have duplicate items.

Collectors can also return Set:

Set<String> distinct = list.stream().collect(Collectors.toSet());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 K9999
Solution 3 Gamaray
Solution 4 Martin Zeitler