简体   繁体   中英

Java stream iterating over a list most efficient way

Given a

 List<User> listUser; //Userobject contains fields userName,userId, forName, last Name

is it possible instead of writing 5 lines to output the user field values

listUser.get(0).getUserName
listUser.get(0).getUserId
listUser.get(0).getforName and so on 

so the output should be

userName -> Hans
userId -> 1
forName -> foo
lastName -> bar

just in one line of code and not having to write 5 lines? ie by stream or something?

listUser.stream().map(s->s.getUserName) //same as above?

One solution would be to write a toString method for the class that has the five lines of code:

public String toString() {
    return "User name: " + getUserName() + "\n" +
           "User ID: " + getUserID() + "\n" +
           "Form name: " + getFormName() + "\n" +
           //...
           ;
}

And then in the Stream you can simply do:

listUser.forEach(System.out::println);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM