英文:
multi level filtering by index of customized list in java 11
问题
不必添加和更新这些额外的连续编号字段,我发现在处理良好排序的多级集合以用于 GUI(其中行索引是即时计算的)时,有两阶段的解决方案很有用:
ParentEntity filterByParentAndChildListsIndexes(List<ParentEntity> parents, Integer prntIdx, Integer chldIdx){
AtomicInteger idx = new AtomicInteger(1); // 可能是 '0'
Optional<ParentEntity> parentOp = parents.stream().filter(p -> idx.getAndIncrement() == prntIdx).findFirst();
if (parentOp.isPresent()){
return childFilter(parentOp.get(), chldIdx);
}
return null;
}
ChildEntity childFilter(ParentEntity parent, Integer chldIdx){
AtomicInteger idx = new AtomicInteger(1); // 可能是 '0'
return parent.getChildEntities().stream().filter(c -> idx.getAndIncrement() == chldIdx).findFirst().orElse(null);
}
但似乎有些冗余且不灵活...因此,我会感激关于现有解决方案或此类多级过滤的递归建议。
英文:
Instead of adding and updating these extra sequential number fields, I found useful two stage solution when processing well sorted multi-level collections for GUI (where row indexes are calculated on fly):
ParentEntity filterByParentAndChildListsIndexes(List<ParentEntity> parents, Integer prntIdx, Integer chldIdx){
AtomicInteger idx = new AtomicInteger(1); // may be '0'
Optional<ParentEntity> parentOp = parents.stream().filter(p -> idx.getAndIncrement() == prntIdx).findFirst();
if (parentOp.isPresent()){
return childFilter(parentOp.get(), chldIdx);
}
return null;
}
ChildEntity childFilter(ParentEntity parent, Integer chldIdx){
AtomicInteger idx = new AtomicInteger(1); // may be '0'
return parent.getChildEntities().stream().filter(c -> idx.getAndIncrement() == chldIdx).findFirst().orElse(null);
}
but it seems redundant and not flexible... so, I would be grateful for suggestions on existing solutions or suggestions for recursion of such multilevel filters.
答案1
得分: 3
你可以这样做:
parents.stream()
.skip(prntIdx)
.limit(1)
.map(ParentEntity::getChildEntities)
.flatMap(Collection::stream)
.skip(chldIdx)
.findFirst()
.orElse(null)
或者只需使用 List.get()
:
if (prntIdx < parents.size()) {
List<ChildEntity> children = parents.get(prntIdx).getChildEntities();
if (chldIdx < children.size()) {
return children.get(chldIdx);
}
}
return null;
英文:
You can do it like this:
parents.stream()
.skip(prntIdx)
.limit(1)
.map(ParentEntity::getChildEntities)
.flatMap(Collection::stream)
.skip(chldIdx)
.findFirst()
.orElse(null)
Or just use List.get()
:
if (prntIdx < parents.size()) {
List<ChildEntity> children = parents.get(prntIdx).getChildEntities();
if (chldIdx < children.size()) {
return children.get(chldIdx);
}
}
return null;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论