Java流迭代列表最有效的方法

给定一个


 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?


拉丁的传说
浏览 62回答 1
1回答

慕哥6287543

一种解决方案是toString为具有五行代码的类编写一个方法:public String toString() {&nbsp; &nbsp; return "User name: " + getUserName() + "\n" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"User ID: " + getUserID() + "\n" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"Form name: " + getFormName() + "\n" +&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;//...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;;}然后Stream您可以简单地执行以下操作:listUser.forEach(System.out::println);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java