我想优化以下代码以采用现有的ArrayList
并根据以下逻辑创建新列表。 Java 8中的流/lambda是否可能?
for (ShipmentTracingDTO tracing : tracings) {
if (tracing.getDestination()) {
newTracings.add(tracing);
break;
}
newTracings.add(tracing);
}
最佳答案
您可以使用IntStream.range
和List.subList
来做到这一点,可能是:
List<ShipmentTracingDTO> newTracings = tracings.subList(0, IntStream.range(0, tracings.size())
.filter(i -> tracings.get(i).getDestination())
.map(a -> a + 1) // to include the index of occurrence
.findFirst()
.orElse(tracings.size())); // else include all until last element
注意:这只是
tracings
的 View ,因此更改基础列表tracings
也将反射(reflect)在newTracings
的更改中。如果您想将它们解耦,则可以从解决方案中创建一个new ArrayList<>()
。编辑:在Holger的评论中,您也可以使用:
List<ShipmentTracingDTO> newTracings = IntStream.rangeClosed(1, tracings.size())
.filter(i -> tracings.get(i - 1).getDestination()) // i-1 to include this as well
.mapToObj(i -> tracings.subList(0, i)) // Stream<List<ShipmentTracingDTO>>
.findFirst() // Optional<List<ShipmentTracingDTO>>
.orElse(tracings); // or else the entire list