Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda expressions in Java 8

Tags:

java

lambda

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?

like image 241
Héctor van den Boorn Avatar asked Jun 07 '15 13:06

Héctor van den Boorn


1 Answers

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.

like image 69
hotkey Avatar answered Oct 22 '22 21:10

hotkey