Getting sonarlint error in eclipse while trying to get value from hashmap

398 views Asked by At

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

3

There are 3 answers

0
Andrius Burokas On BEST ANSWER

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
}
0
v37 On

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);
0
Planck Constant On

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