简体   繁体   中英

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”.

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);

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.

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;

With Stream IPA you can achieve that by using terminal operation allMath() that takes a predicate ( function represented by boolean condition ) and checks whether all elements in the stream match with the given predicate .

The code will look like that:

public static void main(String[] args) {
    List<String> items1 = List.of("apple", "apple", "apple"); // expected true
    List<String> items2 = List.of("apple", "orange"); // expected false

    System.out.println(items1.stream().allMatch(item -> item.equals("apple")));
    System.out.println(items2.stream().allMatch(item -> item.equals("apple")));
}

output

true
false

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

Collectors can also return Set :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM