Home > Enterprise >  Throw exception only in some cases from a list of values in java
Throw exception only in some cases from a list of values in java

Time:06-01

I have a list of values which has maximum of four elements. I need to loop through the list and need to throw exception only in some cases. The different scenarios where the exception needs to be thrown are as follows.

  1. When null value comes in the middle of the list. Some examples are:
 List<String> values = ["test1","test2",null,"test4"];
 List<String> values = ["test1",null,"test3","test4"];
 List<String> values = ["test1",null,null,"test4"];
  1. When null value comes in the beginning of the list. Some examples are:
List<String> values = [null,"test2","test3","test4"];
List<String> values = [null,null,"test3","test4"];
List<String> values = [null,null,null,"test4"];

All other cases are valid ones and should not throw exception. Valid cases are:

List<String> values = ["test1","test2","test3","test4"];
List<String> values = ["test1","test2","test3",null];
List<String> values = ["test1","test2",null,null];
List<String> values = ["test1",null,null,null];
List<String> values = [null,null,null,null];

Can someone please help on this?

CodePudding user response:

You should ensure no non-null elements are present following a null. Otherwise, you will throw an exception

boolean nullSeen = false;
for (String s : list) {
    if (s == null) {
        nullSeen = true;
    } else if (nullSeen) { // for a non-null string
        throw new RuntimeException("Non-null value followed a null");
    }
}

For each element, we check if it is null and if so, we set the boolean flag, nullSeen. And if we encounter a non-null string with nullSeen already set to true, we throw an exception.


If you are using Java 9 and would prefer a stream based solution, then we can use the dropWhile method.

boolean noNonNullValueAfterNull = list.stream()
            .dropWhile(Objects::nonNull) //dropWhile(s -> s != null)
            .allMatch(Objects::isNull); //allMatch(s -> s == null)

if (!noNonNullValueAfterNull) {
    throw new RuntimeException("Non-null value followed a null");
}

From the stream created out of the list, it drops the prefix of elements till it sees a null. The rest of the elements in the stream must be null for the return value to be true.

Note: For an empty stream (all nulls), it will return true which is what we want as well.

  • Related