关于java8新特性中的lambda表达式,静态方法引用以及stream api迭代的写法

查看:129
本文介绍了关于java8新特性中的lambda表达式,静态方法引用以及stream api迭代的写法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

初学java8的语法,对于单独使用lambda表达式,1.8的静态方法引用表示法以及1.8的streamapi中forEach()的引用已经有了一个初步了解,但是在做练习的过程中,遇到了如下代码:

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;
    }

 

对于这部分内容,如果全部改写成1.8的写法,应该如何改写最漂亮?初学这部分内容,比如对于new runnable部分,如果是lambda表达式再串联着EXECUTOR::submid方法和Stearm.forEach()使用的话,语法上总是会报错,而且相关资料较少,查询了很多资料也没有解决,希望有前辈可以用1.8的语法形式把以上代码改写一下,以便更好的理解java8的新特性。

解决方案

看了一下,刨去异常处理,可以改写为以下代码:

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

这篇关于关于java8新特性中的lambda表达式,静态方法引用以及stream api迭代的写法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆