Will I be able to turn this Consumer into a lambda

as indicated in the header. I want to convert this code to lambda if 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;
    }
});
+4
source share
2 answers

This is impossible, no.

Lambdas cannot have a state (outside of any state that they capture from the surrounding context). Even if they could, it would be a little inconvenient to access it, because it thisrefers to the surrounding context (that is, to an object whose method is defined by a lambda), and not an instance of lamdba. This is specified in JLS 15.27.2 .

- AtomicReference<String> , lastLine; , , , . Lambdas , , , ( 15.27.2) , this ).

+7

, 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]);
+1

All Articles