0

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
    }
}
5
  • So, if both are null you get "nullABC", is this what you want?
    – Rocco
    Commented Apr 22, 2021 at 10:03
  • yes @Rocco that's what's expected Commented Apr 22, 2021 at 10:05
  • 1
    …and it’s impossible that both are non-null?
    – Holger
    Commented Apr 22, 2021 at 15:06
  • yes, it's guaranteed as stated Commented Apr 22, 2021 at 15:08
  • 2
    Optional.ofNullable(l.get(0)).orElse(l.get(1)) + "ABC" would do, but I’d rather stay with your original code.
    – Holger
    Commented Apr 22, 2021 at 15:15

1 Answer 1

3

Stream the list, filter non-null elements and find the first.

If you don't find anything, you can say "use null instead":

l.stream().filter(Objects::nonNull).findFirst().orElse(null)

Then just add the "ABC" to the end.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.