将两个流合并为一个

韦诺

考虑以下代码:

// ...
String currentName = ...
String newName = ...; // possibly same as currentName.
                      // in such a case, no exception should be thrown

AnimalEntity animal = animalKeeper.getAnimals()
    .stream()
    .filter(a -> a.getName().equals(currentName))
    .findFirst()
    .orElseThrow(() -> new NoResourceException("No animal with that name"));


if (animalKeeper.getAnimals()
    .stream()
    .filter(a -> !a.getName().equals(currentName))
    .anyMatch(a -> a.getName().equals(newName))) {
  throw new BadRequestException("You already have animal with that name");
}

// ...

该代码可以正常工作,但是我不满意需要在流中进行两次迭代。

我能以某种方式一次达到相同的结果吗?

乔普·艾根(Joop Eggen)

该代码浓缩为:

  • 无操作检查(新名称为旧名称)
  • 所有的动物不包含这个新名字
  • 你可以用它的老名字找到动物

所以:

if (!newName.equals(oldName)) {
    if (animalKeeper.getAnimals().stream()
            .anyMatch(a -> a.getName().equals(newName))) {
        throw new BadRequestException("You already have animal with that name");
    }
    Animal animal = animalKeeper.getAnimals().stream()
            .filter(a -> a.getName().equals(oldName))
            .findAny()
            .orElseThrow(throw new NoResourceException("No animal with that name"));
    animal.rename("Koniara");
}

一个重要的改进将是能够找到名字的动物

if (!newName.equals(oldName)) {
    if (animalKeeper.mapByName.containsKey(newName)) {
        throw new BadRequestException("You already have animal with that name");
    }
    Animal animal = animalKeeper.mapByName.get(oldName);
    if (animal == null) {
        throw new NoResourceException("No animal with that name"));
    }
    animal.rename("Koniara"); // remove+put
}

HashMap可以使速度更快。

您可以在一个流中最多收集2种动物的旧名称或新名称。但它不会改变时间复杂度:N个步和一个分支。同样,只有在收集的结果大小为2时,才可以停止循环。这肯定看起来并不好。2单独的查询可以更快。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章