Beginner's syntax of java8, for using lambda expressions
alone, 1.8's static method reference
notation and 1.8's stream
api forEach I already have a preliminary understanding of the reference of ()
, but during the exercise, I encountered the following code:
public class Java8 {
private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
public static NavigableSet<String> getUniqueAndNavigableLowerCaseMakeNames(VehicleLoader vehicleLoader) {
Region[] regions = Region.values();
final CountDownLatch latch = new CountDownLatch(regions.length);
final Set<VehicleMake> uniqueVehicleMakes = new HashSet<>();
for (Region region : regions) {
EXECUTOR.submit(new Runnable() {
@Override public void run() {
List<VehicleMake> regionMakes = vehicleLoader.getVehicleMakesByRegion(region.name());
if (regionMakes != null) {
uniqueVehicleMakes.addAll(regionMakes);
}
latch.countDown();
}
});
}
try {
latch.await();
} catch (InterruptedException ie) {
Thread.currentThread().interrupt();
throw new RuntimeException(ie);
}
NavigableSet<String> navigableMakeNames = new ConcurrentSkipListSet<>();
for (VehicleMake make : uniqueVehicleMakes) {
if (make.getName() == null) {
continue;
}
navigableMakeNames.add(make.getName().toLowerCase());
}
return navigableMakeNames;
}
For this part of the content, if it is all rewritten to the 1.8 writing method, how should it be rewritten in the most beautiful way? For beginners, for example, for the new runnable part, if lambda expression
is used in series with the EXECUTOR::submid
method and Stearm.forEach()
, grammatical errors are always reported, and there is less relevant information. I have searched a lot of information and still have no solution. I hope that some seniors can rewrite the above code using the 1.8 syntax form to better understand the new features of Java8.
看了一下,刨去异常处理,可以改写为以下代码:
先把 匿名内部类改成 箭头函数 在将for改为forEach