0

Java stream operators can sometimes become very cumbersome and hard to debug. Is there a best practice guideline as to how complex your lambda expression should be beyond which it is better to write an elaborate multi-statement piece of code?

For example, I came across below two statement code for finding factorial which was hard to understand:

Stream<Pair> allFactorials = Stream.iterate(
  new Pair(BigInteger.ONE, BigInteger.ONE),
  x -> new Pair(
    x.num.add(BigInteger.ONE),
    x.value.multiply(x.num.add(BigInteger.ONE))));
return allFactorials.filter(
  (x) -> x.num.equals(num)).findAny().get().value;
4
  • 1
    What is your problem statement? What do you need to achieve here? Commented Feb 7, 2020 at 6:51
  • 1
    You can always create a method that returns the lambda and that way you can add semantics to the stream and simplify the code at the same time, at least for reading purposes (which seems to be what you're looking for). Commented Feb 7, 2020 at 6:56
  • @Ravindra: I was trying to revise my Java concepts for an interview and came across this tutorial where this was used as an example for lambda expressions. My question is if this code is a good use of lambda expressions? If not, what are the best-avoided scenarios when using lambda? Commented Feb 7, 2020 at 7:17
  • Nope. This example is pure "how not to do it". For an interview, it is nice if you know your language well enough to find such "clever" solutions, for day-to-day practice you will be fired/not hired for writing unmaintainable code. Commented Feb 7, 2020 at 7:24

1 Answer 1

3

Java streams are not a silver bullet and you don't have to use it everywhere. There are a lot of cases where you could solve the problem using standard for loop approach.

As for your code.. It is a good example where streams complicate the code and make it hard to understand/maintain. But still there are few solutions are more readable.

Take a look: calculating factorial using Java 8 IntStream?

Sign up to request clarification or add additional context in comments.

1 Comment

Java streams are not a silver bullet +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.