Why? java lambda expression (without outer referenced variables) has same hashcode in loop

Viewed 384

lambda expression in the "for loop" or "streams foreach" has 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());
        });
    }

}

in other case ; i added outer referrenced variable code , in lambda expression body block;

like this ->

                            cs = (list) -> {
                            t.hashCode(); // <---- !!!
                            System.out.println("------start");
                            list.forEach(it -> {
                                System.out.println(it);
                            });
                            System.out.println("------end");
                        };

this code print different hashcode..

(ㅜ..ㅜ)

1 Answers
Related