How to compare all objects in an iterator with compareTo

I have a model class Personthat implements an interface Comparableand a method compareTo(Personne o)that returns the correct int depending on the person's age.

Usecase: I want to check if all faces inside the collection are of the same age with the iterator

What I still have:

while (collectionOfPerson.hasNext()) {
    Person pers = collectionOfPerson.next();
    if (pers.comparTo(collectionOfPerson.next()) == 0) {

    }
}
+3
source share
3 answers

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) {
        // Found mismatch, abort
        return false;
    }
}
// Didn't found mismatch
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());
+4

Usecase: ,

Iterator, , , getAge Person collectionOfPerson :

if (!collectionOfPerson.hasNext()) {
    return;
}

int age = collectionOfPerson.next().getAge();

collectionOfPerson.stream()
                  .mapToInt(Person::getAge)
                  .allMatch(i -> i == age);

, Iterator<Person>, ! boolean , - :

if (!collectionOfPerson.hasNext()) {
    return;
}

int age = collectionOfPerson.next().getAge();

boolean allMatch = true;

while (collectionOfPerson.hasNext()) {
    if (collectionOfPerson.next().getAge() != age) {
        allMatch = false;
        break;
    }
}

if (allMatch) {
    // All of the ages are the same!
}
+3

, .

Optional<Person> anyPerson = persons.stream().findAny();

boolean allSameAge = persons.stream()
    .allMatch(p -> p.compareTo(anyPerson.get()) == 0);

, , .

DDD, , compareTo , Person :

public boolean hasSameAge(Person p);
+2

Source: https://habr.com/ru/post/1694496/


All Articles