如何比较迭代器中的每个对象和compareTo

时间:2018-03-05 22:37:26

标签: java

我有一个模型class Person,它实现Comparable接口和compareTo(Personne o)方法,根据人的年龄返回正确的int。

用例:我想检查集合中的所有人是否与迭代器具有相同的年龄

到目前为止我所拥有的:

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

    }
}

3 个答案:

答案 0 :(得分:3)

  

用例:我想检查集合中的所有人是否与迭代器具有相同的年龄

如果您愿意,可以利用流和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!
}

答案 1 :(得分:3)

仅仅抓住第一个人并将其与其他人进行比较就足够了,因为您正在测试是否所有人都具有相同的年龄。

另外,你的比较是不对的,你有:

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;

Stream不使用Iterator的示例:

Person first = persons.iterator().next();

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

使用增强型for循环(for-each)的替代方法:

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());

答案 2 :(得分:2)

我提倡只使用流的一种解决方案。

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);