给定一个 List<User> listUser; //Userobject contains fields userName,userId, forName, last Name是否可以不用写 5 行来输出用户字段值listUser.get(0).getUserNamelistUser.get(0).getUserIdlistUser.get(0).getforName and so on 所以输出应该是userName -> HansuserId -> 1forName -> foolastName -> bar只需一行代码而无需编写 5 行?即通过流或其他方式?listUser.stream().map(s->s.getUserName) //same as above?
1 回答
慕哥6287543
TA贡献1831条经验 获得超10个赞
一种解决方案是toString为具有五行代码的类编写一个方法:
public String toString() {
return "User name: " + getUserName() + "\n" +
"User ID: " + getUserID() + "\n" +
"Form name: " + getFormName() + "\n" +
//...
;
}
然后Stream您可以简单地执行以下操作:
listUser.forEach(System.out::println);
添加回答
举报
0/150
提交
取消