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;
}
});
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).
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]);
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