Java List forEach Lamba 表达式 - 第一个元素并遍历所有元素

Kri*_*ish 5 java foreach lambda

我可以循环遍历 List 的所有元素,如下所示:

userList.forEach(user -> {
    System.out.println(user);
});
Run Code Online (Sandbox Code Playgroud)

我只想为第一个元素打印用户对象,但我应该为列表中的所有元素循环。如何做到这一点?

And*_*ddo 1

如果您想将某些逻辑应用于第一个用户并继续与其他用户循环,那么您可以使用条件来检查第一个对象是否是当前对象。据我从你的问题中了解到,这就是你想要的

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)

  • 对我来说似乎不是最理想的,在每次迭代中获取第一个项目,然后与“user”进行比较,我会在循环之前进行此检查。 (2认同)
  • @Aomine,我同意,但是,如果用户多次出现在列表中,则意味着相同的对象,那么我认为问题中可能会指出这一点,但如果用户重复作为不同的对象,这仍然有效,毕竟为什么我会在同一个列表中重复用户对象!所以我只是认为用户更有可能在那里,但不是相同的对象,并且功能将如需要的那样。然而,所有这一切都取决于问题,并且根本没有表明这一点,因此,假设:) (2认同)