Java 8 不使用终端操作就可以知道流的大小
我有3个接口Java 8 不使用终端操作就可以知道流的大小,java-8,java-stream,Java 8,Java Stream,我有3个接口 public interface IGhOrg { int getId(); String getLogin(); String getName(); String getLocation(); Stream<IGhRepo> getRepos(); } public interface IGhRepo { int getId(); int getSize(); int getWatchers
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();
}
IGhOrg公共接口{
int getId();
字符串getLogin();
字符串getName();
字符串getLocation();
流getRepos();
}
公共接口IGhRepo{
int getId();
int getSize();
int getWatchersCount();
字符串getLanguage();
流getContributors();
}
公共接口IGhUser{
int getId();
字符串getLogin();
字符串getName();
字符串getCompany();
流getOrgs();
}
我需要实现可选的最高级贡献者(流组织)
此方法返回包含大多数参与者的IGhRepo(getContributors())
我试过这个
Optional<IGhRepo> highestContributors(Stream<IGhOrg> organizations){
return organizations
.flatMap(IGhOrg::getRepos)
.max((repo1,repo2)-> (int)repo1.getContributors().count() - (int)repo2.getContributors().count() );
}
可选最高贡献者(流组织){
返回组织
.flatMap(IGhOrg::getRepos)
.max((repo1,repo2)->(int)repo1.getContributors().count()-(int)repo2.getContributors().count());
}
但它给了我
java.lang.IllegalStateException:流已被操作或关闭
我知道count()是流中的一个终端操作,但我不能解决这个问题,请帮助
谢谢您没有指定此项,但看起来,返回
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);
}
可选最高贡献者(流组织){
返回组织
.flatMap(IGhOrg::getRepos)
.distinct()
.map(repo->newAbstractMap.SimpleEntry(repo,repo.getContributors().count())
.max(Map.Entry.comparingByValue())
.map(map.Entry::getKey);
}
不幸的是,如果您想(例如)打印参与者列表,您现在可能会被卡住,因为从返回的IGhRepo
的getContributors()
返回的流已经被使用
你可能想考虑你的实现对象每次调用一个流返回方法时返回一个新的流。
不使用终端操作就可以知道流的大小 不,不是这样,因为流可以是无限的,也可以按需生成输出。它们没有必要由集合支持 但它给了我 这是因为每次方法调用都返回相同的流实例。您应该返回一个新的流 我知道count()是流中的一个终端操作,但我不能解决这个问题,请帮助 我知道你在滥用这里的溪流。性能和简单性方面,返回一些集合
,而不是流
否。
这不可能知道java
中流的大小
如中所述
没有存储空间。流不是存储元素的数据结构;
相反,它从数据结构等源传送元素,
通过管道的阵列、生成器函数或I/O通道
关于计算运算
似乎
getContributors()
不会返回新的流,但如果不知道实现,就无法确定。
java.lang.IllegalStateException: stream has already been operated upon or closed