關于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的新特性。
問題解答
回答1:看了一下,刨去異常處理,可以改寫為以下代碼:
return Arrays.stream(Region.values()).flatMap(region -> vehicleLoader.getVehicleMakesByRegion(region.name()).stream()).distinct().filter(make -> make.getName() != null).collect(Collectors.toCollection(ConcurrentSkipListSet::new));回答2:
先把 匿名內部類改成 箭頭函數 在將for改為forEach
