0

I successfully sort students by id using comparator and displayed using for loop, I hope to know how can I make it happen with iterator, well I tried but only address in console and have no idea of how to print info from Student class

public static void main(String[] args) {
    Student stu1 = new Student("Lucy",1000,99);
    Student stu2 = new Student("Jack",1001,22);
    Student stu3 = new Student("Peter",1002,53);

    ArrayList<Student> student = new ArrayList<Student>();
    student.add(stu1);
    student.add(stu2);
    student.add(stu3);

    Collections.sort(student,new StuCOmp("id"));
    for (int i=0; i<student.size(); i++) {
        Student stu = student.get(i);
        System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());    
    }

    Iterator<Student> it = student.iterator();
    while(it.hasNext()){

        //what do I write here
    }
}
3

6 Answers 6

1

You can iterate it like this in for loop -

       for (Iterator<Student> iterator = student.iterator(); iterator.hasNext();) {
            Student stu = iterator.next();
            System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());
        }
Sign up to request clarification or add additional context in comments.

3 Comments

You shouldn't use a raw Iterator. Use an Iterator<Student>
@Suresh:Thanks, once Iterator<Student> is used, no need to caste.
@JavaLearner Yes. Now it seems ok. +1.
1
Iterator<Student> it = student.iterator();
    while(it.hasNext()){
        // You should write here:   
        Student stu = it.next();
        System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());
     }

Comments

1
Iterator itr=student.iterator();  
  while(itr.hasNext()){  
    Student stu=(Student)itr.next();  
    System.out.println(stu.getName() + " "+stu.getId()+ " "+stu.getGrade());  

1 Comment

the sys out prints the object means as hash code of object student will be printed. No use of it.
1

You can avoid using an iterator and use an enhanced for loop.

for (Student st : student)
    System.out.println(st.getName() + " "+st.getId()+ " "+st.getGrade());

Comments

0

You can do something like this

Iterator<Student> it = student.iterator();
while(it.hasNext()){
  Student student=it.next();// you can get the students one by one  
  // Now you can get the each student info
  //student.any attribute
}

This way is very similar to for-each but iterator is faster than that.

Comments

0
Iterator itr=student.iterator();  
  while(itr.hasNext()){  
    Student stu=(Student)itr.next();  
    System.out.println("whatever you want to print");  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.