What for? java lambda expression (no external reference variables) has the same hashcode in a loop
lambda expression in "for loop" or "streams foreach" has the same hashcode. Why?
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("Mukesh", "Vishal", "Amar" ,"Ansony");
list.stream().collect(Collectors.groupingBy(
new Function<String, Consumer<List<String>>>() {
Map<String, Consumer<List<String>>> map = new HashMap<String, Consumer<List<String>>>();
@Override
public Consumer<List<String>> apply(String t) {
String key = t.substring(0,1);
Consumer<List<String>> cs = map.get(key);
if(cs == null) {
cs = (list) -> {
System.out.println("------start");
list.forEach(it -> {
System.out.println(it);
});
System.out.println("------end");
};
map.put(key, cs);
}
System.out.println("group key Consumer hashcode : "+ cs.hashCode());
return cs;
}
}
))
.entrySet()
.forEach( entry -> {
System.out.println("key : " + entry.getKey());
System.out.println("value : " + entry.getValue());
entry.getKey().accept(entry.getValue());
});
}
}
otherwise; I added the outer code of the labeled variable in the body block of the lambda expression;
like this β
cs = (list) -> {
t.hashCode(); // <---- !!!
System.out.println("------start");
list.forEach(it -> {
System.out.println(it);
});
System.out.println("------end");
};
this code prints different hash codes.
(γ .. γ )
source to share
Your question seems to be why the hashCodes are the same for the first case (without t.hashCode
) and why it is different when added t.hashCode
.
@ holi-java pointed you in the right direction - the first is called a stateless
lambda - and as such in the current implementation you will always get a singleton - the same instance Consumer
will be reused for all calls.
Once you make it stateful (by adding an external variable - in your case t.hashCode
) - you just made it a stateful lambda - and within the current implementation, you get new instance of a Consumer
each time - thus your output is a different hashcode.
The more interesting thing is that this is only useful for debugging - since you cannot override hashCode
either equals
or toString
to express a lambda - so other than understanding how some things work - this information is pretty useless.
source to share