MicroLova
MicroLova

Reputation: 361

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? i.e by stream or something?

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

Upvotes: 0

Views: 68

Answers (1)

GBlodgett
GBlodgett

Reputation: 12819

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);

Upvotes: 1

Related Questions