摘要:陳楊一表達(dá)式與流二初始化測試數(shù)據(jù)三各種方法一方法方法二方法
package com.java.design.java8; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.time.*; import java.time.format.DateTimeFormatter; import java.time.temporal.ChronoField; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * @author 陳楊 * */ @SpringBootTest @RunWith(SpringRunner.class) public class LambdaInfo {一、Lambda表達(dá)式與Stream流
/* A lambda expression can be understood as a concise representation of an anonymous function that can be passed around: it doesn’t have a name, but it has a list of parameters, a body, a return type, and also possibly a list of exceptions that can be thrown. That’s one big definition; let’s break it down: Anonymous: We say anonymous because it doesn’t have an explicit name like a method would normally have: less to write and think about! Function: We say function because a lambda isn’t associated with a particular class like a method is. But like a method, a lambda has a list of parameters, a body, a return type, and a possible list of exceptions that can be thrown. Passed around: A lambda expression can be passed as argument to a method or stored in a variable. Concise: You don’t need to write a lot of boilerplate like you do for anonymous classes. */ /* Stream : A sequence of elements from a source that supports data processing operations. Sequence of elements Source Pipelining Internal iteration Traversable only once Collections: external interation using an interator behind the scenes */二、初始化測試數(shù)據(jù)
private List三、各種APIlist; @Before public void init() { list = IntStream.rangeClosed(1, 100).boxed().collect(Collectors.toList()); list.sort(Collections.reverseOrder()); }
1.allMatch
@Test public void testLambdaInfo() { System.out.println(">---------------------Match方法----------------------<"); // 一、Match方法 // Returns whether all elements of this stream match the provided predicate. Optional.of(list.stream().mapToInt(Integer::intValue).allMatch(i -> i > 0)) .ifPresent(System.out::println); // Returns whether any elements of this stream match the provided predicate. Optional.of(list.stream().mapToInt(Integer::intValue).anyMatch(i -> i > 0)) .ifPresent(System.out::println); // Returns whether no elements of this stream match the provided predicate.. Optional.of(list.stream().mapToInt(Integer::intValue).noneMatch(i -> i > 0)) .ifPresent(System.out::println);
2、find
System.out.println(">--------------------Find方法-----------------------<"); // 二、Find方法 // Returns an Optional describing the first element of this stream, // or an empty Optional if the stream is empty. // If the stream has no encounter order, then any element may be returned. list.stream().mapToInt(Integer::intValue).filter(i -> i > 10).findFirst() .ifPresent(System.out::println); // Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. list.stream().mapToInt(Integer::intValue).filter(i -> i > 10).findAny() .ifPresent(System.out::println);
3、reduce
System.out.println(">---------------------Reduce方法----------------------<"); // 三、Reduce方法 // Performs a reduction on the elements of this stream, using the provided identity value // and an associative accumulation function, and returns the reduced value. // 求和 System.out.println(list.stream().reduce(0, Integer::sum)); list.stream().mapToInt(Integer::intValue).reduce(Integer::sum) .ifPresent(System.out::println); // 求最大值 System.out.println(list.stream().reduce(0, Integer::max)); list.stream().mapToInt(Integer::intValue).reduce(Integer::max) .ifPresent(System.out::println); // 求最小值 System.out.println(list.stream().reduce(0, Integer::min)); list.stream().mapToInt(Integer::intValue).reduce(Integer::min) .ifPresent(System.out::println); System.out.println(">-------------------------------------------<"); }
4、CompletableFuture API
@Test public void testCompletableFuture() { // 四、CompletableFuture API /* * Returns a new CompletableFuture that is asynchronously completed by a task * running in the given executor with the value obtained by calling the given Supplier. */ CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum, System.out::println); Optional.of(CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .complete(55)).ifPresent(System.out::println); // thenAccept 無返回值 Consumer super T> action CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .thenAccept(System.out::println); // thenApply 有返回值 Function super T,? extends U> fn CompletableFuture.supplyAsync(() -> list.stream().mapToInt(Integer::intValue)) .thenApply(IntStream::sum).thenAccept(System.out::println); // 對元素及異常進(jìn)行處理 BiFunction super T, Throwable, ? extends U> fn CompletableFuture.supplyAsync(() -> list.stream().mapToInt(Integer::intValue)) .handle((i, throwable) -> "handle: " + i.sum()).thenAccept(System.out::println); // whenCompleteAsync 完成時(shí)執(zhí)行 BiConsumer super T, ? super Throwable> action CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .whenCompleteAsync((value, throwable) -> System.out.println("whenCompleteAsync: " + value)); // 組合CompletableFuture 將前一個結(jié)果作為后一個輸入?yún)?shù) (參照 組合設(shè)計(jì)模式) CompletableFuture.supplyAsync(() -> list.stream().mapToInt(Integer::intValue)) .thenCompose(i -> CompletableFuture.supplyAsync(i::sum)).thenAccept(System.out::println); // 合并CompletableFuture CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .thenCombine(CompletableFuture.supplyAsync(() -> list.stream() .mapToDouble(Double::valueOf).sum()), Double::sum).thenAccept(System.out::println); // 合并CompletableFuture CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue)::sum) .thenAcceptBoth(CompletableFuture.supplyAsync(list.stream() .mapToDouble(Double::valueOf)::sum), (r1, r2) -> System.out.println("thenAcceptBoth: " + r1 + " " + r2)); // 2個CompletableFuture運(yùn)行完畢后運(yùn)行Runnable CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + " is running"); return list.stream().mapToInt(Integer::intValue).sum(); }) .runAfterBoth( CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + " is running"); return list.stream().mapToDouble(Double::valueOf).sum(); }), () -> System.out.println("The 2 method have done")); // 2個CompletableFuture 有一個運(yùn)行完就執(zhí)行Runnable CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + " is running"); return list.stream().mapToInt(Integer::intValue).sum(); }) .runAfterEither( CompletableFuture.supplyAsync(() -> { System.out.println(Thread.currentThread().getName() + " is running"); return list.stream().mapToDouble(Double::valueOf).sum(); }), () -> System.out.println("The 2 method have done")); // 2個CompletableFuture 有一個運(yùn)行完就執(zhí)行Function super T, U> fn CompletableFuture.supplyAsync( list.stream().mapToInt(Integer::intValue).max()::getAsInt) .applyToEither( CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue).min()::getAsInt) , v -> v * 10) .thenAccept(System.out::println); // 2個CompletableFuture 有一個運(yùn)行完就執(zhí)行Consumer super T> action CompletableFuture.supplyAsync( list.stream().mapToInt(Integer::intValue).max()::getAsInt) .acceptEither( CompletableFuture.supplyAsync(list.stream().mapToInt(Integer::intValue).min()::getAsInt) , System.out::println); // 將集合中每一個元素都映射成為CompletableFuture對象 List > collect = list.stream().map(i -> CompletableFuture.supplyAsync(i::intValue)) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); // 集合轉(zhuǎn)數(shù)組 CompletableFuture[] completableFutures = collect.toArray(CompletableFuture[]::new); // 有一個task執(zhí)行完畢 CompletableFuture.anyOf(completableFutures) .thenRun(() -> System.out.println("有一個task執(zhí)行完畢--->first done")); // 有且僅有所有task執(zhí)行完畢 CompletableFuture.allOf(completableFutures) .thenRun(() -> System.out.println("有且僅有所有task執(zhí)行完畢--->done")); }
5、Java.time API
@Test public void testLocalDateTime() { // 五、Java.time API LocalDate localDate = LocalDate.of(2019, 12, 1); // 當(dāng)前時(shí)間 Optional.of(LocalDate.now()).ifPresent(System.out::println); // 年份 Optional.of(localDate.getYear()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.YEAR)).ifPresent(System.out::println); // 月份 (Jan-->Dec) Optional.of(localDate.getMonth()).ifPresent(System.out::println); // 月份(1-->12) Optional.of(localDate.getMonthValue()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.MONTH_OF_YEAR)).ifPresent(System.out::println); // 年中的第幾天 Optional.of(localDate.getDayOfYear()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.DAY_OF_YEAR)).ifPresent(System.out::println); // 月中的第幾天 Optional.of(localDate.getDayOfMonth()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.DAY_OF_MONTH)).ifPresent(System.out::println); // 星期幾(Mon-->Sun) Optional.of(localDate.getDayOfWeek()).ifPresent(System.out::println); // 星期幾(1-->7) OptionalInt.of(localDate.get(ChronoField.DAY_OF_WEEK)).ifPresent(System.out::println); // 時(shí)代(公元前、后) CE BCE Optional.of(localDate.getEra()).ifPresent(System.out::println); // 時(shí)代(公元前、后) 1--->CE 0--->BCE Optional.of(localDate.getEra().getValue()).ifPresent(System.out::println); OptionalInt.of(localDate.get(ChronoField.ERA)).ifPresent(System.out::println); // ISO年表 Optional.of(localDate.getChronology().getId()).ifPresent(System.out::println); // 當(dāng)前時(shí)間 LocalTime time = LocalTime.now(); // 時(shí) OptionalInt.of(time.getHour()).ifPresent(System.out::println); OptionalInt.of(time.get(ChronoField.HOUR_OF_DAY)).ifPresent(System.out::println); // 分 OptionalInt.of(time.getMinute()).ifPresent(System.out::println); OptionalInt.of(time.get(ChronoField.MINUTE_OF_DAY)).ifPresent(System.out::println); // 秒 OptionalInt.of(time.getSecond()).ifPresent(System.out::println); OptionalInt.of(time.get(ChronoField.SECOND_OF_DAY)).ifPresent(System.out::println); // 納秒 OptionalInt.of(time.getNano()).ifPresent(System.out::println); OptionalLong.of(time.getLong(ChronoField.NANO_OF_SECOND)).ifPresent(System.out::println); // 中午時(shí)間 Optional.of(LocalTime.NOON).ifPresent(System.out::println); // 午夜時(shí)間 Optional.of(LocalTime.MIDNIGHT).ifPresent(System.out::println); // 自定義格式化時(shí)間 DateTimeFormatter customDateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss E"); LocalDateTime localDateTime = LocalDateTime.of(localDate, time); Optional.of(localDateTime.format(customDateTimeFormatter)).ifPresent(System.out::println); // 根據(jù)傳入的文本匹配自定義指定格式進(jìn)行解析 Optional.of(LocalDateTime.parse("2019-12-25 12:30:00 周三", customDateTimeFormatter)) .ifPresent(System.out::println); // 時(shí)間點(diǎn) Instant Instant start = Instant.now(); try { Thread.sleep(10_000); } catch (InterruptedException e) { e.printStackTrace(); } Instant end = Instant.now(); // Duration 時(shí)間段 Duration duration = Duration.between(start, end); OptionalLong.of(duration.toNanos()).ifPresent(System.out::println); // Period 時(shí)間段 Period period = Period.between(LocalDate.now(), localDate); OptionalInt.of(period.getYears()).ifPresent(System.out::println); OptionalInt.of(period.getMonths()).ifPresent(System.out::println); OptionalInt.of(period.getDays()).ifPresent(System.out::println); // The Difference Between Duration And Period // Durations and periods differ in their treatment of daylight savings time when added to ZonedDateTime. // A Duration will add an exact number of seconds, thus a duration of one day is always exactly 24 hours. // By contrast, a Period will add a conceptual day, trying to maintain the local time. } }四、備注
1、Why do we need a new date and time library? https://www.oracle.com/technetwork/articles/java/jf14-date-time-2125367.html 2、java.time API https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/73658.html
摘要:表達(dá)式體現(xiàn)了函數(shù)式編程的思想,即一個函數(shù)亦可以作為另一個函數(shù)參數(shù)和返回值,使用了函數(shù)作參數(shù)返回值的函數(shù)被稱為高階函數(shù)。對流對象進(jìn)行及早求值,返回值不在是一個對象。 Java8主要的改變是為集合框架增加了流的概念,提高了集合的抽象層次。相比于舊有框架直接操作數(shù)據(jù)的內(nèi)部處理方式,流+高階函數(shù)的外部處理方式對數(shù)據(jù)封裝更好。同時(shí)流的概念使得對并發(fā)編程支持更強(qiáng)。 在語法上Java8提供了Lamb...
摘要:新特性總覽標(biāo)簽本文主要介紹的新特性,包括表達(dá)式方法引用流默認(rèn)方法組合式異步編程新的時(shí)間,等等各個方面。還有對應(yīng)的和類型的函數(shù)連接字符串廣義的歸約匯總起始值,映射方法,二元結(jié)合二元結(jié)合。使用并行流時(shí)要注意避免共享可變狀態(tài)。 Java8新特性總覽 標(biāo)簽: java [TOC] 本文主要介紹 Java 8 的新特性,包括 Lambda 表達(dá)式、方法引用、流(Stream API)、默認(rèn)方...
摘要:陳楊一流的定義流支持串行并行聚合操作元素序列二流的創(chuàng)建流的創(chuàng)建以方法生成流三 package com.java.design.java8.Stream.StreamDetail; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframe...
摘要:內(nèi)部迭代與使用迭代器顯式迭代的集合不同,流的迭代操作是在背后進(jìn)行的。流只能遍歷一次請注意,和迭代器類似,流只能遍歷一次。 流(Stream) 流是什么 流是Java API的新成員,它允許你以聲明性方式處理數(shù)據(jù)集合(通過查詢語句來表達(dá),而不是臨時(shí)編寫一個實(shí)現(xiàn))。就現(xiàn)在來說,你可以把它們看成遍歷數(shù)據(jù)集的高級迭代器。此外,流還可以透明地并行處理,你無需寫任何多線程代碼了!我會在后面的筆記中...
摘要:首先我們定義一個有兩個不同控制器的然后,我們創(chuàng)建一個特定的工廠接口來創(chuàng)建新的對象不需要手動的去繼承實(shí)現(xiàn)該工廠接口,我們只需要將控制器的引用傳遞給該接口對象就好了的控制器會自動選擇合適的構(gòu)造器方法。這種指向時(shí)間軸的對象即是類。 本文為翻譯文章,原文地址 這里 歡迎來到本人對于Java 8的系列介紹教程,本教程會引導(dǎo)你一步步領(lǐng)略最新的語法特性。通過一些簡單的代碼示例你即可以學(xué)到默認(rèn)的接口方...
閱讀 2775·2023-04-25 14:15
閱讀 2712·2021-11-04 16:11
閱讀 3402·2021-10-14 09:42
閱讀 452·2019-08-30 15:52
閱讀 2833·2019-08-30 14:03
閱讀 3554·2019-08-30 13:00
閱讀 2119·2019-08-26 11:40
閱讀 3317·2019-08-26 10:25