I'm getting error like "Call "Optional#isPresent()" before accessing the value" , while trying to get value from hashmap.
Code:
String promolevelname = eventCampiagnResponseObj.getEventCampMap().get(Integer.valueOf(sceobj[18].toString())).keySet().stream().findFirst().get();
Please give me a solution to resolve this issue, Thanks
findFirst
returns Optional
but it will throw NoSuchElementException
if there is no value. So you need to check if there is a value present.
Optional<String> value = obj.getOptional()
if (value.isPresent()) {
value.get();
}
In your situation it should look like this:
Optional<String> optionalValue = eventCampiagnResponseObj.getEventCampMap().get(Integer.valueOf(sceobj[18].toString())).keySet().stream().findFirst();
if (optionalValue .isPresent()) {
String promolevelname = optionalValue.get();
}
It suggests that the code line
eventCampiagnResponseObj.getEventCampMap().get(Integer.valueOf(sceobj[18].toString())).keySet().stream().findFirst()
is returning an Optional object, which you should check if it's not 'null' and only then execute get() on it.
One possible solution would be this:
Optional<String> promolevelnameOpt = eventCampiagnResponseObj.getEventCampMap().get(Integer.valueOf(sceobj[18].toString())).keySet().stream().findFirst().get();
if (promolevelnameOpt.isPresent()) {
promolevelname = promolevelnameOpt.get();
} else {
// promolevelnameOpt contains null
}
Instead of .get()
you could use .orElse(null)
So your code becomes:
String promolevelname = eventCampiagnResponseObj.getEventCampMap().get(Integer.valueOf(sceobj[18].toString())).keySet().stream().findFirst().orElse(null);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.