I have two strings in a list. Now either of them or both of of the strings could be null
. And I'll be concatenating the string in this list which is not null
, with another string say ABC
. It's guaranteed the list would have only two elements and either one or both of the strings will be null.
If both are null
output will be nullABC
My solution looks like this:
public class Main {
public static void main(String[] var0) {
List<String> l = Arrays.asList(null,"sfdafd");
String str = (l.get(0)!=null ? l.get(0) : l.get(1)) + "ABC" ;
System.out.println(str); // sfdafdABC
}
}
null
?Optional.ofNullable(l.get(0)).orElse(l.get(1)) + "ABC"
would do, but I’d rather stay with your original code.