我可以像下面这样遍历所有列表元素:
我想只打印列表的第一个元素的用户对象,但我应该循环所有元素。如何实现?
list中的所有元素均可通过以下方式循环:
userList.forEach(user -> {
System.out.println(user);
});
我想只打印列表的第一个元素的用户对象,但我应该循环所有元素。如何实现?
看起来你想问如何打印第一个对象但是迭代剩余元素并执行一些其他逻辑,此时你可以选择:
if(!userList.isEmpty()) System.out.println(userList.get(0));
userList.subList(1, userList.size()).forEach(user -> ...);
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");
});
// 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");
);
// 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);
});
// 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);
});
user
对象的来源,使用==
可能无法正常工作。 - Óscar Lópezfor-each
的解决方案。List<String> userList = Arrays.asList("2","3","4");
IntStream.range(0, userList.size()).forEach(i -> {
if (i == 0)
System.out.println(userList.get(i));
else {
System.out.println("do other stuff");
}
});
输出:
2
do other stuff
do other stuff
for (int i = 0; i < Long.MAX_VALUE; i++){ if (i == 0)
{} //...}` - zlakad如果您正在使用lambda表达式,那么在JDK9中这里有另一种解决方案:
IntStream.range(0, userList.size())
.peek(i -> {if(i == 0) System.out.println(userList.get(i));})
.dropWhile(i -> i == 0)
.forEach(i -> /* some other logic here */ );
就个人而言,以及对于生产代码而言,我会选择我的另一个答案,但如果你只是在玩lambda,那么上面的方法也是你可以采用的。
这应该可以工作
userList.foreach(user -> {
If(user == userList.get(0){
System.out.println(user)
}
})