Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check whether a List<String> contains a specific string?

Tags:

java

loops

list

Here's what I'm trying to do: I have some List<String>, I want to print a statement if the List contains a particular string, else throw an Exception but when I try the following code

List<String> fruit = new ArrayList<>();
fruit.add("apple");
fruit.add("orange");
fruit.add("banana");

for(int i = 0; i < fruit.size(); i++){
   if(fruit.get(i).contains("banana"){
     System.out.println("Found");
   } else {
     throw new SkipException("could not be found");
   }
}

it iterates through the List and at i = 0 it obviously finds "apple" and immediately goes to the else block and throws exception. I also tried the following, but this didn't work either.

for(int i = 0; i < fruit.size(); i++){
   if(Arrays.asList(fruit).contains("banana"){
      System.out.println("found");
   }else{
      throw new SkipException("not found");
   }
}

Is there an easy way to do what I'm trying to do here?

like image 769
DjShon Avatar asked May 19 '16 17:05

DjShon


1 Answers

There are a few ways.

Which one you choose is up to you, there's a tradeoff between verbosity, being constrained to a simple equals check (if you want to do more complicated matching, you can't easily do Option 1), and using newer APIs that you might not yet support or be familiar with.

Option 1: The Collection.contains() method:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

if (fruits.contains("banana") {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 2: Using a for loop with external state:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

boolean found = false;
for (String s : fruits) {
    if (s.equals("banana")) {
        found = true;
        break; // Break out of the loop to skip the remaining items
    }
}
if (found) {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 3: If you're using Java 8, the neat Stream.anyMatch() method:

List<String> fruits = new ArrayList<>();
fruits.add("apple");
fruits.add("orange");
fruits.add("banana");

if (fruits.stream().anyMatch(s -> s.equals("banana"))) {
    System.out.println("Found");
} else {
    throw new SkipException("could not be found");
}

Option 3 is my personal favorite, as it's nearly as compact as Option 1, but allows to to provide a more complex Predicate if you want a comparison based on something other than the equals() method.

like image 102
Craig Otis Avatar answered Sep 18 '22 04:09

Craig Otis