Search code examples
javalambdatry-catchrunnable

How to make a anonymous class with void return type method and no parameters into a lambda expression?


I have the following piece of code where I need to change it into a lambda expression (Sonarlint presents this as an issue)

      Runnable runnableObj = new Runnable() {
        @Override
        public void run() {
          try {
            myObj.setParameters(Id);
          } catch (Exception e) {
            LOG.info("Exception in setting parameters for user" + Id);
          }
        }
      }

I tried to change this into

       Runnable runnableObj = ()->{
          try {
            myObj.setParameters(Id);
          } catch (Exception e) {
            LOG.info("Exception in setting parameters for user" + Id);
          }

      }

I am not sure if this the correct way to do it. Please help as I have not implemented lambda expressions previously.


Solution

  • This is the correct implementation. The lambda expressions takes no arguments as the run() method doesn't, and it contains the same implementation.