Search code examples
javalambda

use increment inside lambda in java


I have a block like this

int i = 0;
shaders.forEach((WrappedShader shader) -> 
{
    int shader_id = glCreateShader(shader.getShader_type());
    glShaderSource(shader_id, shader.getShader_source());
    glCompileShader(shader_id);
    glAttachShader(shader_program, shader_id);
    shader_ids[i++] = shader_id;
});

But how to have increment inside lambda? Currently it asks to set the variable i as final and do not change it.

I know I can rewrite it to for loop but I'd like to use lambda.


Solution

  • Ideally, for functional program you should have pure functions with no side effects. In this case, you have side effects but you could do is

    int[] sharedIds = shaders.stream().mapToInt((WrappedShader shader) -> {
                int shader_id = glCreateShader(shader.getShader_type());
                glShaderSource(shader_id, shader.getShader_source());
                glCompileShader(shader_id);
                glAttachShader(shader_program, shader_id);
                return shared_id;
          }).toArray();