What is the difference between a ‘closure’ and a ‘lambda’?

Could someone explain? I understand the basic concepts behind them but I often see them used interchangeably and I get confused. And now that we’re here, how do they differ from a regular function? 15 s 15 There is a lot of confusion around lambdas and closures, even in the answers to this StackOverflow question … Read more

Java 8 List into Map

I want to translate a List of objects into a Map using Java 8’s streams and lambdas. This is how I would write it in Java 7 and below. private Map<String, Choice> nameMap(List<Choice> choices) { final Map<String, Choice> hashMap = new HashMap<>(); for (final Choice choice : choices) { hashMap.put(choice.getName(), choice); } return hashMap; } … Read more

Why would you use Expression rather than Func?

I understand lambdas and the Func and Action delegates. But expressions stump me. In what circumstances would you use an Expression<Func<T>> rather than a plain old Func<T>? 1Best Answer 11 When you want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the … Read more

Is there a reason for C#’s reuse of the variable in a foreach?

When using lambda expressions or anonymous methods in C#, we have to be wary of the access to modified closure pitfall. For example: foreach (var s in strings) { query = query.Where(i => i.Prop == s); // access to modified closure … } Due to the modified closure, the above code will cause all of … Read more

local variables referenced from a lambda expression must be final or effectively final

You can just copy the value of readln2 into a final variable: final String labelText = readln2 ; Button button = new Button(“Click the Button”); button.setOnAction(e -> l.setText(labelText)); If you want to grab a new random line each time, you can either cache the lines of interest and select a random one in the event handler: Button button = … Read more

Variable used in lambda expression should be final or effectively final

A final variable means that it can be instantiated only one time. in Java you can’t reassign non-final local variables in lambda as well as in anonymous inner classes. You can refactor your code with the old for-each loop: private TimeZone extractCalendarTimeZoneComponent(Calendar cal,TimeZone calTz) { try { for(Component component : cal.getComponents().getComponents(“VTIMEZONE”)) { VTimeZone v = … Read more