Check the list if String, if not contains throw error in Java

Viewed 47

Objective: The task of determining whether the provided String is a part of one of the string elements in the list.


String userInput = "Detailed"

List<String> list = Arrays.asList("C - Consolidated",
                "D - Detailed",
                "P - Corp. Consolidated",
                "N - No Statement",
                "O - Corporate",
                "S - Summary",
                "Y - Mail Statement",
                "M - Summary - store name",
                "I - Summary - 1 page");

my expectation is

if userInput is not in List then throw new IllegalArgumentException("Invalid") I am looking for solution in Java. I tired using StreamApi and for each but nothing worked for me.

4 Answers

If I understand correctly your question, your trying to verify if the array contains the user output.

From your question I'm guessing you tried to do as you would do in python, but that doesn't work in Java

To check wether a list contains an item or not in Java, you have to use the list function "contains"

It should look something like that :

if list.contains(userInput) {
 dosomething
}

I tired using StreamApi and for each but nothing worked for me.

The task of determining whether the provided String is a part of one of the string elements in the list is fairly straightforward:

boolean isPresent = list.stream()
    .anyMatch(s -> s.contains(userInput));
    
System.out.println(isPresent); // would print - `true`
        
if (isPresent) {
    throw new Exception();
}

If you need to throw a checked exception, you can do it like shown above (outside the stream), or implement the same logic using for-loop:

for (String s : list) {
    if (s.contains(userInput)) {
        throw new RuntimeException();
    }
}

Note:

  • It's not possible to throw checked exceptions while using standard functional interfaces from the JDK.
  • It highly advisable to avoid using general exception types like Exception and instead pick that gives the most description to your case, or create your custom exception.

But you can throw RuntimeException and it's subtypes. The example below would compile successfully, and at runtime if the result contains a value RuntimeException would be propagated from the consumer.

list.stream()
    .filter(s -> s.contains(userInput))
    .findFirst()
    .ifPresent(s -> { throw new RuntimeException(); });

The first option is:

    if (!list.contains(userInput)) {
        throw new RuntimeException();
    }

The second:

    boolean isUserInputInList = list.stream().anyMatch(listElement -> listElement.equals(userInput));
    if (!isUserInputInList) {
        throw new RuntimeException();
    }

Note that the user input is compared word for word, in other words to receive true in comparing it should be exact the same as in list, e.g. "D - Detailed". Also, I recommend you to use RuntimeException() instead of Exception. You can read here https://www.java67.com/2012/12/difference-between-runtimeexception-and-checked-exception.html why.

Walk through the List. If you find a match then return, otherwise throw the exception. The only thing notable here is that you can shortcircuit the iteration if you find the word - hence the break statement.

public void checkList(String word, List<String> list) {
  boolean present = false;
  for (String element : list) {
    if (element.contains(word)) {
      present = true;
      break;
    }
  }
  if (!present) {
    throw new RuntimeException(word + " is not in List");
  }
}

You could use the Stream API to find the element and then react to it not being present by throwing an exception.

if (!list.stream().filter(element -> element.contains(word)).findFirst().isPresent()) {
  throw new RuntimeException(word + " is not in List");
}
Related