加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java-8 – 可以在不使用终端操作的情况下知道流的大小

发布时间:2020-12-15 04:34:46 所属栏目:Java 来源:网络整理
导读:我有3个接口 public interface IGhOrg { int getId(); String getLogin(); String getName(); String getLocation(); StreamIGhRepo getRepos();}public interface IGhRepo { int getId(); int getSize(); int getWatchersCount(); String getLanguage(); St
我有3个接口

public interface IGhOrg {
    int getId();

    String getLogin();

    String getName();

    String getLocation();

    Stream<IGhRepo> getRepos();
}

public interface IGhRepo {
    int getId();

    int getSize();

    int getWatchersCount();

    String getLanguage();

    Stream<IGhUser> getContributors();
}

public interface IGhUser {
    int getId();

    String getLogin();

    String getName();

    String getCompany();

    Stream<IGhOrg> getOrgs();
}

我需要实现Optional< IGhRepo>最高贡献者(Stream< IGhOrg>组织)

此方法返回与大多数贡献者的IGhRepo(getContributors())

我试过这个

Optional<IGhRepo> highestContributors(Stream<IGhOrg> organizations){
    return organizations
            .flatMap(IGhOrg::getRepos)
            .max((repo1,repo2)-> (int)repo1.getContributors().count() - (int)repo2.getContributors().count() );
}

但它给了我

java.lang.IllegalStateException: stream has already been operated upon or closed

我明白count()是Stream中的终端操作但是我无法解决这个问题,请大家帮忙!

谢谢

解决方法

您没有指定此内容,但它看起来像返回Stream< ...>的一些或可能所有接口方法每次调用时,值都不会返回新流.

从API的角度来看,这对我来说似乎有问题,因为它意味着这些流中的每一个,并且对象功能的一大部分最多可以使用一次.

您可以通过确保每个对象的流只在方法中使用一次来解决您遇到的特定问题,如下所示:

Optional<IGhRepo> highestContributors(Stream<IGhOrg> organizations) {
  return organizations
      .flatMap(IGhOrg::getRepos)
      .distinct()
      .map(repo -> new AbstractMap.SimpleEntry<>(repo,repo.getContributors().count()))
      .max(Map.Entry.comparingByValue())
      .map(Map.Entry::getKey);
}

不幸的是,如果你想(例如)打印一个贡献者列表,你似乎会陷入困境,因为从getContributors()返回的流已经被消耗了返回的IGhRepo.

您可能希望在每次调用流返回方法时考虑让实现对象返回新流.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读