I want to generate a list of numbers using lambda expressions and not a for-loop.
So let's say I want to generate a list of all triangular numbers under 100. Triangular numbers are numbers which follow the formula: (n*n+n)/2
What is the best way of doing this? Currently 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 overkill with the amount of calculations. I iterate n over 1 to 100 (because lets assume I do not know what the max value for n is), then I map the triangle number function of that list and then I check which numbers are under 100. Is there a more efficient way in doing this? Also: can I generate the triangle numbers using only the iterate function of Stream instead of using iterate, limit and then map?
EDIT: So the main point here is: how can calculation of traingle numbers stop as soon as one of the triangle numbers exceeds 100? Usually I would write it like 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);
}
which stops as soon as a triangle number exceeds 100, which is very efficient; how can I retain this efficiency in lambda expression?
In general case what you're looking for is take-while. Unfortunately, it has no default implementation in Java 8 streams. See a question about take-while.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With