javasonarlint-eclipse

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


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


Solution

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