Home > Software engineering >  What’s the best way to check if a list contains an item other than specified item?
What’s the best way to check if a list contains an item other than specified item?

Time:03-04

I have a list and I want to know if there exist elements in it that are not a particular value.

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

How do it return false if items contains an element other than some String, say "apple"?

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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;

CodePudding user response:

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

CodePudding user response:

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

Collectors can also return Set:

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