给出
List<User> listUser; //Userobject contains fields userName,userId, forName, last Name
是否可以代替编写5行来输出用户字段值
listUser.get(0).getUserName
listUser.get(0).getUserId
listUser.get(0).getforName and so on
所以输出应该是
userName -> Hans
userId -> 1
forName -> foo
lastName -> bar
只需一行代码,而不必编写5行?即通过流或其他方式?
listUser.stream().map(s->s.getUserName) //same as above?
答案 0 :(得分:1)
一种解决方案是为具有五行代码的类编写一个toString
方法:
public String toString() {
return "User name: " + getUserName() + "\n" +
"User ID: " + getUserID() + "\n" +
"Form name: " + getFormName() + "\n" +
//...
;
}
然后在Stream
中,您可以简单地执行以下操作:
listUser.forEach(System.out::println);