About lambda expressions, static method references and stream api iteration in the new features of java8
世界只因有你
世界只因有你 2017-05-17 10:04:45
0
2
802

Beginner's syntax of java8, for using lambda expressions alone, 1.8's static method referencenotation and 1.8's streamapi 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.

世界只因有你
世界只因有你

reply all(2)
刘奇

After taking a look, excluding exception handling, it can be rewritten as the following code:

return Arrays.stream(Region.values())
        .flatMap(region -> vehicleLoader.getVehicleMakesByRegion(region.name()).stream())
        .distinct()
        .filter(make -> make.getName() != null)
        .collect(Collectors.toCollection(ConcurrentSkipListSet::new));
某草草

First change the anonymous inner class to arrow function and then change for to forEach

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template