英文:
How to use multiple filters + map in the same stream?
问题
如何将这两个流合并为一个流?
List<Integer> Type1ErrorRows = errors.stream()
.filter(c -> (c.getClass() == Type1Error.class))
.map(c -> ((Type1Error) c).getRowNumber())
.collect(Collectors.toList());
List<Integer> Type2ErrorRows = errors.stream()
.filter(c -> (c.getClass() == Type2Error.class))
.map(c -> ((Type2Error) c).getRowNumber())
.collect(Collectors.toList());
List<Integer> mergedRows = Stream.concat(Type1ErrorRows.stream(), Type2ErrorRows.stream())
.collect(Collectors.toList());
注意:我只提供了代码的翻译部分,不包括其他内容。
英文:
How do I merge this to a single stream?
List<Integer> Type1ErrorRows = errors.stream()
.filter(c -> (c.getClass() == Type1Error.class))
.map(c -> ((Type1Error) c).getRowNumber())
.collect(Collectors.toList());
List<Integer> Type2ErrorRows = errors.stream()
.filter(c -> (c.getClass() == Type2Error.class))
.map(c -> ((Type2Error) c).getRowNumber())
.collect(Collectors.toList());
EDIT: Sorry, the question is misleading in this form (really stupid of me), I forgot to mention that I want all the row numbers in a single list as a result:
Stream.concat(Type1ErrorRows.stream(), Type2ErrorRows.stream())
.collect(Collectors.toList());
答案1
得分: 1
我会假设存在一个常见的接口,否则所有所需的转换将使流程变得太繁琐。
public interface ErrorInterface {
int getRowNumber();
}
过滤对象的类是否被允许,进行类型转换,调用方法获取行号。
Set<Class<?>> allowedClasses = Set.of(Type1Error.class, Type2Error.class);
List<Integer> rowNumbers = errors.stream()
.filter(err -> allowedClasses.contains(err.getClass()))
.map(err -> (ErrorInterface) err)
.map(ErrorInterface::getRowNumber)
.toList();
英文:
I'll assume that a common interface exists, otherwise all the required casting will make it too cumbersome for streams.
public interface ErrorInterface {
int getRowNumber();
}
Filter that object's class is allowed, cast, invoke method to get row number.
Set<Class<?>> allowedClasses = Set.of(Type1Error.class, Type2Error.class);
List<Integer> rowNumbers = errors.stream()
.filter(err -> allowedClasses.contains(err.getClass()))
.map(err -> (ErrorInterface) err)
.map(ErrorInterface::getRowNumber)
.toList();
答案2
得分: -2
流不是这个任务的正确工具。只需使用循环:
List<Integer> type1 = new ArrayList<Integer>();
List<Integer> type2 = new ArrayList<Integer>();
for (Error error : errors) {
if (error instanceof Type1Error e1) {
type1.add(e1.getRowNumber());
}
else if (error instanceof Type2Error e2) {
type2.add(e2.getRowNumber());
}
}
英文:
Streams are not the right tool for this job. Just use a loop:
List<Integer> type1 = new ArrayList<Integer>();
List<Integer> type2 = new ArrayList<Integer>();
for (Error error : errors) {
if (error instanceof Type1Error e1) {
type1.add(e1.getRowNumber());
}
else if (error instanceof Type2Error e2) {
type2.add(e2.getRowNumber());
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论