Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would I be able to convert this Consumer into a lambda

Tags:

java

lambda

as the title states. I wish to transform this code into lambda would that be possible?

crashFile.forEach(new Consumer<String>() {
    String lastLine;
    @Override
    public void accept(String line) {
        if((title == null || title.equals("")) && line.contains("at")) {
            title = lastLine;
        }
        lastLine = line;
    }
});
like image 244
karelmikie3 Avatar asked Feb 10 '23 05:02

karelmikie3


2 Answers

It's not directly possible, no.

Lambdas can't have state (outside of whatever state they capture from their surrounding context). Even if they could, it'd be a bit awkward to access it, because this refers to the surrounding context (that is, to the object whose method the lambda is defined in), not the lamdba's instance. That's specified in JLS 15.27.2.

You could do something like declaring an AtomicReference<String> right before the lambda, and then using it to manage the lastLine state; but that would probably be an abuse of lambdas, more than an idiomatic use of them. Lambdas are really designed to be pretty stateless, except insofar as they capture their surrounding context's state (which is why 15.27.2) specifies that this references that context, instead of the lambda).

like image 133
yshavit Avatar answered Feb 11 '23 18:02

yshavit


You can't have encapsulated fields but you can have a reference to an array of 1

String[] lastLine = { null };
crashFile.forEach(line -> {
    if((title == null || title.equals("")) && line.contains("at")) {
        title = lastLine[0];
    }
    lastLine[0] = line;
});
System.out.println("The last line was " + lastLine[0]);
like image 44
Peter Lawrey Avatar answered Feb 11 '23 17:02

Peter Lawrey