Java 8 lambda create list of Strings from list of objects

前端 未结 4 1208
自闭症患者
自闭症患者 2021-02-02 10:31

I have the following qustion:

How can I convert the following code snipped to Java 8 lambda style?

List tmpAdresses = new ArrayList

        
相关标签:
4条回答
  • 2021-02-02 10:39

    You can use this to convert Long to String:

    List<String> ids = allListIDs.stream()
                                 .map(listid-> String.valueOf(listid))
                                 .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-02-02 10:41

    One more way of using lambda collectors like above answers

     List<String> tmpAdresses= users
                      .stream()
                      .collect(Collectors.mapping(User::getAddress, Collectors.toList()));
    
    0 讨论(0)
  • 2021-02-02 10:48

    It is extended your idea:

    List<String> tmpAdresses = users.stream().map(user ->user.getAdress())
    .collect(Collectors.toList())
    
    0 讨论(0)
  • 2021-02-02 10:57

    You need to collect your stream into a List:

    List<String> adresses = users.stream()
        .map(User::getAdress)
        .collect(Collectors.toList());
    

    For more information on the different Collectors visit the documentation

    User::getAdress is just another form of writing (User user) -> user.getAdress() which could aswell be written as user -> user.getAdress() (because the type User will be inferred by the compiler)

    0 讨论(0)
提交回复
热议问题