Iterating over two arrays simultaneously using for each loop in Java
Asked Answered
B

5

10

Student's names(String[]) and corresponding marks(int[]) are stored in different arrays.

How may I iterate over both arrays together using for each loop in Java ?

void list() {

    for(String s:studentNames) {
        System.out.println(s); //I want to print from marks[] alongside.
    }
}

One trivial way could be using index variable in the same loop. Is there a good way to do?

Barsac answered 11/10, 2013 at 12:56 Comment(6)
Why is the normal for (one with index variable) not good enough?Disfeature
consider a map. like hashmapAesculapius
It should be noted that it is not very nice design to keep things that have an association in separate arrays. Instead you should use a map or create a simple class with name and mark attributes and have a single array (or list) of these objects.Ginkgo
These two arrays are working in parallel, and their only association is via the index (so you can't use an enhanced for loop because you need to know the index). Stefan rightly points out this is very bad design that offers so little flexibility I don't think it's ever used outside of arbitrary examples.Tetrapody
Like the OP I'm disappointed there's no smarter way of doing it such as for(String s : studentNames, int g : grades) {...}Myron
possible duplicate of Sexy way to iterate over parallel arrays in Java using foreachZoubek
C
9

The underlying problem is actually that you should tie both of the arrays together and iterate across just one array.

Here is a VERY simplistic demonstration - you should use getters and setters and you should also use a List instead of an array but this demonstrates the point:

class Student {
  String name;
  int mark;
}
Student[] students = new Student[10];

for (Student s : students) {
  ...
}
Castro answered 11/10, 2013 at 13:9 Comment(0)
S
14

You need to do it using the regular for loop with an index, like this:

if (marks.length != studentNames.length) {
    ... // Something is wrong!
}
// This assumes that studentNames and marks have identical lengths
for (int i = 0 ; i != marks.length ; i++) {
    System.out.println(studentNames[i]);
    System.out.println(marks[i]);
}

A better approach would be using a class to store a student along with his/her marks, like this:

class StudentMark {
    private String name;
    private int mark;
    public StudentMark(String n, int m) {name=n; mark=m; }
    public String getName() {return name;}
    public int getMark() {return mark;}
}

for (StudentMark sm : arrayOfStudentsAndTheirMarks) {
    System.out.println(sm.getName());
    System.out.println(sm.getMark());
}
Selfjustifying answered 11/10, 2013 at 12:58 Comment(4)
Agreed. There is no way to achieve this with the "foreach" variant of for.Ginkgo
@StefanWinkler At least not without merging the students and their marks into a single object.Selfjustifying
i'd give +2 if i could. perfect answer + better solutionAesculapius
I can't believe some educational institutions teach OO languages, then give examples like this out (re: OP). Objects first, surely? (+1 to this answer)Tetrapody
C
9

The underlying problem is actually that you should tie both of the arrays together and iterate across just one array.

Here is a VERY simplistic demonstration - you should use getters and setters and you should also use a List instead of an array but this demonstrates the point:

class Student {
  String name;
  int mark;
}
Student[] students = new Student[10];

for (Student s : students) {
  ...
}
Castro answered 11/10, 2013 at 13:9 Comment(0)
A
4

If them both have the same size, I would write:

for(int i = 0; i<marks.length; i++) {
    String names= studentNames[i]
    int mark = marks[i];     

}
Ation answered 11/10, 2013 at 12:59 Comment(0)
C
0

The other way is to use a verbose for loop statement such as;

int i,j;
for(i = 0, j=0; i<= student.length-1 && j <=grades.length-1; i++,j++)
{
...
}
Cappella answered 11/10, 2018 at 21:30 Comment(1)
You could just use a single variable i. There will never be a case where i != j. In which case, it's not verbose, and is honestly just the correct way to do it.Apex
T
0

Going with Sergey Kalinichenko's something is wrong:

    if (marks.length != studentNames.length) {
        ... // Something is wrong!
    }
    Iterator<Integer> marks_ = java.util.Arrays.asList(marks).iterator();
    // This assumes that studentNames is no longer than marks
    for (String name: studentNames)
        System.out.println(name + ": " + marks_.next());
Thedathedric answered 3/8, 2023 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.