Kri*_*ish 5 java foreach lambda
我可以循环遍历 List 的所有元素,如下所示:
userList.forEach(user -> {
System.out.println(user);
});
Run Code Online (Sandbox Code Playgroud)
我只想为第一个元素打印用户对象,但我应该为列表中的所有元素循环。如何做到这一点?
如果您想将某些逻辑应用于第一个用户并继续与其他用户循环,那么您可以使用条件来检查第一个对象是否是当前对象。据我从你的问题中了解到,这就是你想要的
userList.forEach(user -> {
if (userList.get(0) == user)
System.out.println("This is user with index 0");
System.out.println(user + " All users including 0");
});
Run Code Online (Sandbox Code Playgroud)
正如 Aomine 在评论中所说,这可能不是每次检查列表第一个元素的好解决方案,并且如果列表中重复相同的用户对象,则可能无法正常工作,因此最好将这样的逻辑分开
// Do something with the first user only
if(!userList.isEmpty())
System.out.println(userList.get(0));
// Do some stuff for all users in the list except the first one
userList.subList(1, userList.size()).forEach(user -> {
System.out.println(user + " All users without 0");
);
// Do some stuff for all users in the list
userList.forEach(user -> {
System.out.println(user + " All users");
);
Run Code Online (Sandbox Code Playgroud)
另一种使用流的方法
// Dealing with first user only
if (!userList.isEmpty()) {
System.out.println("this is first user: " + userList.get(0));
}
// using stream skipping the first element
userList.stream().skip(1).forEach(user -> {
System.out.println(user);
});
Run Code Online (Sandbox Code Playgroud)
您也可以使用迭代器方法
// getting the iterator from the list
Iterator<String> users = userList.iterator();
// the first user
if(users.hasNext())
System.out.println("this is first user :" + users.next());
// the rest of the users
users.forEachRemaining(user -> {
System.out.println(user);
});
Run Code Online (Sandbox Code Playgroud)