I have a List<String> list = Arrays.asList("test1","test2","test3","test4");
I want to achive something like this:
String cCN = "";
boolean flag = true;
list.forEach(ele -> {
if (ele.equals("test3")) {
cCN = ele;
flag = false;
}
});
This is not allowed since lambda expression can only access effectively final or final variables. IDE suggests using AtomicRefrence for this, but I was thing if there is any other way to do it.
It is considered as a bad practice to write lambdas that have heavy side effects as your example. Correct way to do it using stream API would be using filter function like:
List<String> list = Arrays.asList("test1","test2","test3","test4");
Optional<String> cCN = list
.stream()
.filter(s -> s.equals("test3"))
.findFirst();
It is generally considered a bad practice to use side effects in Java Stream API operations. Stream operations should be designed to produce output based solely on their input, without modifying any external state. Stream API is designed to allow for functional-style processing of collections or arrays of data.
One of the key features of functional programming is that functions should be pure, meaning that they should not have any side effects and should only rely on their input arguments to produce output.