Compacting if else statement into shorter more elegant code [duplicate]

  • A+

This question already has an answer here:

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; } 

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); 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: