Puedo capaz de recorrer todos los elementos de la lista, como a continuación:
userList.forEach(user -> {
System.out.println(user);
});
Quiero imprimir el objeto de usuario única para el primer elemento pero debería bucle para todos los elementos de la lista. ¿Cómo lograr eso?
Si desea aplicar cierta lógica al primer usuario y continuar bucle con otros, entonces puede utilizar para comprobar la condición del primer objeto es la corriente o no. A medida que entiendo de su pregunta, esto es lo que quiere
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");
});
Como dijo Aomine en los comentarios, esto podría no ser gran solución para la comprobación del primer elemento de la lista cada vez y podría no funcionar correctamente si el mismo objeto de usuario se repite en la lista para mejor separar la lógica como esto
// 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");
);
Otro abordaje con corriente
// 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);
});
También es posible utilizar iterador se acercan
// 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);
});