findFirst() gives you an Optional and you then have to decide what to do if it's not present. So findFirst().orElse(null) should give you the object or null if it's not present
You could just do a .get() on the Optional, but that could be regarded as poor practice since get() will throw an exception if Optional has no content. You should normally assert presence/absence of the Optional and decide what to do in each case (that's why it's there - so that you know something is truly optional and you have to determine what to do)
If you have an action you want to perform on object presence, and you don't want to do anything on absence, you can call .ifPresent() and provide a lambda as an argument. That will be called with the contained object, if present.
As of Java 9, a further solution would be to use Optional.ifPresentOrElse()
Answer from Brian Agnew on Stack OverflowVideos
findFirst() gives you an Optional and you then have to decide what to do if it's not present. So findFirst().orElse(null) should give you the object or null if it's not present
You could just do a .get() on the Optional, but that could be regarded as poor practice since get() will throw an exception if Optional has no content. You should normally assert presence/absence of the Optional and decide what to do in each case (that's why it's there - so that you know something is truly optional and you have to determine what to do)
If you have an action you want to perform on object presence, and you don't want to do anything on absence, you can call .ifPresent() and provide a lambda as an argument. That will be called with the contained object, if present.
As of Java 9, a further solution would be to use Optional.ifPresentOrElse()
I think you may be looking for findFirst().or Else(null). findFirst() will return an Optional - empty in the case of an empty steam.
Unless I misunderstood your comment. Have you tried this, or did you try orElse(null) without findFirst()?
You can use object spread to have an optional property:
let flag1 = true;
let flag2 = false;
// extra cases added by Abdull
let optionalKey8 = 8;
let optionalKey9 = undefined;
let optionalKey10 = false;
let optionalKey11 = null;
let optionalKey12 = "twelve";
const obj = {
requiredKey1: 1,
requiredKey2: 2,
...(flag1 && { optionalKey3: 3 }),
...(flag2 && { optionalKey4: 4, optionalKey5: 5 }), // ignored
...(flag1 && { optionalKey6: 6, optionalKey7: 7 }),
...(optionalKey8 && { optionalKey8 }),
...(optionalKey9 && { optionalKey9 }), // ignored
...(optionalKey10 && { optionalKey10 }), // ignored
...(optionalKey11 && { optionalKey11 }), // ignored
...(optionalKey12 && { optionalKey12 })
};
console.log(obj);
To indicate optional key, you can assign to it null, if the condition is false
const someCondition = true;
const obj = {
requiredKey1: 1,
requiredKey2: 2,
optionalKey1: someCondition ? 'optional' : null
};
console.log(obj);