Java stream API: are there syntax sugar for identity functor?

只谈情不闲聊 提交于 2019-12-01 16:10:01

问题


We use several Map as simple memory DB over list of objects:

class Person {
    public String id;
    public String phone;
    public String email;
    // and get/set and other fields...
}

List<Person> persons;
Map<String, Person> emailLookup = persons.stream()
        .collect(Collectors.toMap(Person::getEmail, p -> p));
Map<String, Person> phoneLookup = persons.stream()
        .collect(Collectors.toMap(Person::getPhone, p -> p));
Map<String, Person> idLookup = persons.stream()
        .collect(Collectors.toMap(Person::getId, p -> p));

Are there any syntax sugar or built-in functor in Java SE to replace p -> p with something else?


回答1:


You could use Function.identity() but if you want short then I don't think you'll beat your existing p -> p.



来源:https://stackoverflow.com/questions/28222784/java-stream-api-are-there-syntax-sugar-for-identity-functor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!