Lambda expressions in Java 8
I want to use a lambda expression instead of a for loop to generate a list of numbers
So let's want to generate a list of all triangle numbers below 100 Trigonometry is the number of the following formula: (n * n) / 2
What is the best way to do this? At present, I have this:
Stream.iterate(1,n -> n + 1).limit(100) .map(n -> (n * n + n) / 2) .filter(a -> a < 100) .map(a -> a + "") .collect(Collectors.joining(",","Numbers: ","."));
But this seems unnecessarily over - calculated I iterate over n from 1 to 100 (because assuming I don't know what the maximum value of n is), then I map the trigonometric function of the list, and then I check which numbers are below 100. Is there a more effective way to do this? In addition, I can use the iterate function of stream to generate triangular numbers instead of iterate, limit, and then map?
Editor: so the point here is: once one of the triangle numbers exceeds 100, how does the calculation of a number stop? I usually write this:
ArrayList<Integer> triangles = new ArrayList<>(); for (int n=1;true;n++) { int num = (n*n+n)/2; if (num>100) break; triangles.add(num); }
Once the triangle number exceeds 100, it stops, which is very effective; How do I preserve this efficiency in lambda expressions?
Solution
In general, what you are looking for is a period of time