AtomicInteger has already been mentioned. Mutable Double can be emulated using AtomicReference<Double> . The warnings already mentioned apply and this is bad style, but sometimes you have code similar to this
double sum=0 for (Data data:someListGenerator()) sum+=data.getValue()
and you want to reorganize it in the functional style of Java 8. If the code follows this template, but gives it more complexity, the most reasonable transformation may be
AtomicReference<Double> sumref=new AtomicReference<>(0d); someStreamGenerator().forEach(data-> sumref.set(sumref.get().doubleValue()+data.getValue())); double sum=sumref.get().doubleValue();
Of course, this is at least a dubious style. But I found myself more than once in a twisted-loop situation over calculating a ResultSet and partially cumulating three different data. This makes it difficult to convert the code to the correct functional style. Converting the cumulative parts in accordance with the above example seemed to me a reasonable compromise between clean code and simplified refactoring.
Dirk Hillbrecht Aug 14 '16 at 10:08 on 2016-08-14 10:08
source share