Function.identity()的含義


偶然之間發現的這個函數,感覺還是很有用的,尤其實在返回map的時候,value還為本身,用起來就很方便。

Java 8允許在接口中加入具體方法。接口中的具體方法有兩種,default方法和static方法,identity()就是Function接口的一個靜態方法。
Function.identity()返回一個輸出跟輸入一樣的Lambda表達式對象,等價於形如t -> t形式的Lambda表達式

@Test public void test() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("hepengju", 28, 20000.0));
        personList.add(new Person("lisi"    , 44, 40000.0));
        personList.add(new Person("wangwu"  , 55, 50000.0));
        personList.add(new Person("zhaoliu" , 66, 60000.0));
        personList.add(new Person("zhangsan", 33, 33333.0));
        personList.add(new Person("wgr", 23, 10000.0));
        Map<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity()));
        collect.forEach((name,p) ->{
            System.out.println(name + ":"+p);
        });
 

    }

 但是改成同一個名字的時候就會報錯

 修改如下:

@Test public void test() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("hepengju", 28, 20000.0));
        personList.add(new Person("lisi"    , 44, 40000.0));
        personList.add(new Person("wangwu"  , 55, 50000.0));
        personList.add(new Person("zhaoliu" , 66, 60000.0));
        personList.add(new Person("zhangsan", 33, 33333.0));
        personList.add(new Person("zhangsan", 23, 10000.0));
        ConcurrentHashMap<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new));
        collect.forEach((name,p) ->{
            System.out.println(name + ":"+p);
        });

如果想返回 Map<String, Map<Integer, Person>>,可以這樣寫。
 Map<String, Map<Integer, Person>> collect = personList.stream().collect(Collectors.toMap(Person::getName, p -> {
            Map<Integer, Person> map = new HashMap<>();
            map.put(p.getAge(), p);
            return map;
        }));
        collect.forEach( (name,p) ->{
            System.out.println(name + ":"+p);
        });


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM