[Java] Lambda should not be too complex or too long

A very large Lambda can make it difficult to follow the logic surrounding it. It also makes the code more difficult to maintain.


  list.forEach(number -> IntStream.range(0, number).forEach(j -> System.out.println(number * j)));


  for (Integer number : list) {
  	for (int j = 0; j < number; j++) {
  		System.out.println(number * j);


In order for us to consider this suggestion we would need a bit more information.
Could you give a bit more details about the reasoning behind this suggestion ?
Why is the noncompliant example “bad” ?

Moreover, could you give a little more detail about what could be the threshold to raise an issue ? what would it take for the lambda to be “too long or too complex” ? What is the criteria ?


Hi Nicolas,

The idea behind this rule is to avoid the overused of lambdas and streams. In this non-compliant example,
it’s easy overlook that this one is nested. In a even more complicated case, it will only get harder to understand.

About that threshold, it really depends on which intermediate stream operations are used. For example filter(...) and map(...) are quite easy to follow up, if the conditions or method are kept simple (lambdas should be short as possible, ideally a method reference). On the other hand using flatmap(...) will make it much more harder to follow.

Since we aren’t really expert in this field, maybe you could try to figure out when this certain threshold is reach. For example using filter() with a simple lambda condition gives 1 point. Using filter() with a more complex lambda gives 3 Points. After reaching a certain number of points you could raise an issue.



I believe this feature is already partly covered by https://rules.sonarsource.com/java/RSPEC-1188 and its configuration.

I think the title and some parts of the explanation is misleading.
We would like to have a rule which addresses the complexity of a stream expression (which may contain several lambdas).
But I don’t have a good example at the moment for a complex stream. I will search for it.

@Holger_Mensch, please open a new topic, once you have the example. You can reference this one with link, if you think it is relevant.