It is enough to capture only the first person and compare it with every other person, since you are testing if everyone is of the same age.
In addition, your comparison is incorrect, you have:
pers.comparTo(collectionOfPerson.next()) == 0
, . , . , , , . . , , , .
, , .
Person first = collectionOfPerson.next();
while (collectionOfPerson.hasNext()) {
Person other = collectionOfPerson.next();
if (first.comparTo(other) != 0) {
return false;
}
}
return true;
a Stream , Iterator:
Person first = persons.iterator().next();
boolean allSameAge = persons.stream()
.allMatch(p -> p.compareTo(first) == 0);
for ( ):
Person first = persons.iterator().next();
for (Person other : persons) {
if (other.compareTo(first) != 0) {
return false;
}
}
return true;
, . :
Person first = persons.iterator().next();
List<Person> otherAgePersons = persons.stream()
.filter(p -> p.compareTo(first) != 0)
.collect(Collectors.toList());