1

I have the following if-else block, and I'm wondering if there's a more elegant way this code could be written... I am using Java 8

if(valueString != null) {
    return valueString;
}
else if(valueInt != null) {
    return String.valueOf(valueInt);
}
else if(valueFloat != null) {
    return String.valueOf(valueFloat);
}
else if(valueDate != null){
    return String.valueOf(valueDate);
}
else if(valueBit != null) {
    return String.valueOf(valueBit);
}
else {
    return null;
}
Morteza Jalambadani
  • 2,190
  • 6
  • 21
  • 35
user1501171
  • 210
  • 1
  • 3
  • 17

1 Answers1

15

Use a stream and go through all the values and return null if none of them is not null.

return Stream.of(valueString, valueInt, valueFloat, valueDate, valueBit)
             .filter(Objects::nonNull)
             .map(String::valueOf)
             .findFirst().orElse(null);
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 3
    @YassinHajaj instead of `x -> x != null` you can use `Objects::nonNull`. I find a method reference looking nicer than a lambda, but that's really just a preference. – Jaroslaw Pawlak May 03 '18 at 11:43