Rya*_*n S 0 java design-patterns java-stream
我有这个流,以及其他一些人,我滥用了一堆电话来完成工作.当利用J8时,似乎是一种反模式.
+ Arrays.stream(resources)
+ .map(this::ingestFromFile)
+ .collect(Collectors.toList())
+ .stream()
+ .map(Container.class::cast)
+ .map(Container::getAll)
+ .flatMap(Collection::stream)
+ .collect(Collectors.toList())
+ .forEach(
+ dataType -> {
+ loaderConstants.getRepo(dataType.toString()).save(dataType);
+ LOGGER.log(Level.INFO, "Saved: " + dataType);
+ });
Run Code Online (Sandbox Code Playgroud)
我怎样才能缩短这一点,将来我应该注意哪些陷阱以避免这种类型的开发?
好吧,你不需要中间 .collect(Collectors.toList())调用,因为它是不必要的,并导致可避免的开销.
Arrays.stream(resources)
.map(this::ingestFromFile)
.map(Container.class::cast)
.map(Container::getAll)
.flatMap(Collection::stream)
.forEach(
dataType -> {
loaderConstants.getRepo(dataType.toString()).save(dataType);
LOGGER.log(Level.INFO, "Saved: " + dataType);
});
Run Code Online (Sandbox Code Playgroud)
然后你可以提取forEach一个方法的主体来简化管道.