Santosh Santosh - 3 months ago 4x
Java Question

what is the best way to iterate a list and exit in java

I have an list of students object; I want to find out if at least one student have valid ID or not. if all of them in the list have a invalid ID or blank ID then I should exist and throw an exception. What is the best way of doing it in JAVA ?


List<Student> Students;
class Student {
int ID;
String Name;
int Marks;

Student one
ID = 1,name = Ram,Marks = 50

Student two
ID = "",name = Syam,Marks = 60

Student three
ID = 2,name = Sudan,Marks = 70

boolean isAllInvalid= true;
for(Student student : students){ 
 if(student.getID() != null && studend.getID() >=1 ){// this checks for a valid id 
  system.out.print(student+ " has a valid id");
  isAllInvalid =false; 
  break;//early exit no need to keep looping cuz we found at least one valid id ,if you to print all valid remove the break statement.
   throw new SomeException("All students are invalid") ;//choose ur suitable exception