0

I need help regarding changing lambda expression to method reference:

lambda expression:

intervalCodes.stream().forEach(code -> {
            modProfile.addIntervalUsageCode(createIntervalCode(code));
          });

Can I change the above expression to like this:

intervalCodes.stream().forEach(modProfile::addIntervalUsageCode(createIntervalCode));

Any suggestions please?

mrs
  • 207
  • 2
  • 5
  • 13
  • My suggestion: leave the code as is. You're calling two methods, so you can't change it to a single method reference. You could try some kind of function composition (see http://stackoverflow.com/questions/19834611/how-to-do-function-composition), but that's not likely to improve your code. – ajb Mar 31 '17 at 06:30
  • If you want to be concise, remove the obsolete braces and if `intervalCodes` is a `Collection`, omit the Stream operation, which is unnecessary, if all you want to do, is `forEach`: `intervalCodes.forEach( code -> modProfile.addIntervalUsageCode(createIntervalCode(code)));` – Holger Mar 31 '17 at 11:43

1 Answers1

5

Assuming createIntervalCode() is a side-effect-free instance method, you can split your lambda into two method references:

intervalCodes.stream()
        .map(this::createIntervalCode)
        .forEach(modProfile::addIntervalUsageCode);

If it's a static method, use ClassName::createIntervalCode.

shmosel
  • 49,289
  • 6
  • 73
  • 138
  • `createIntervalCode` has a parameter `code` as stated in OP's question: `code -> { modProfile.addIntervalUsageCode(createIntervalCode(code));}`. Will the method reference still work? – walen Mar 31 '17 at 07:05
  • @walen Certainly. `map()` expects a `Function`, which takes an input parameter. – shmosel Mar 31 '17 at 07:07