本篇主要講述是Java中JDK1.8的一些新語法特性使用,主要是Lambda、Stream和LocalDate日期的一些使用講解。html
Lambda 表達式(lambda expression)是一個匿名函數,Lambda表達式基於數學中的λ演算得名,直接對應於其中的lambda抽象(lambda abstraction),是一個匿名函數,即沒有函數名的函數。java
下面咱們先使用一個簡單的例子來看看Lambda的效果吧。git
好比咱們對Map 的遍歷
傳統方式遍歷以下:程序員
Map<String, String> map = new HashMap<>(); map.put("a", "a"); map.put("b", "b"); map.put("c", "c"); map.put("d", "d"); System.out.println("map普通方式遍歷:"); for (String key : map.keySet()) { System.out.println("k=" + key + ",v=" + map.get(key)); }
使用Lambda進行遍歷:github
System.out.println("map拉姆達表達式遍歷:"); map.forEach((k, v) -> { System.out.println("k=" + k + ",v=" + v); });
List也同理,不過List還能夠經過雙冒號運算符遍歷:數據庫
List<String> list = new ArrayList<String>(); list.add("a"); list.add("bb"); list.add("ccc"); list.add("dddd"); System.out.println("list拉姆達表達式遍歷:"); list.forEach(v -> { System.out.println(v); }); System.out.println("list雙冒號運算符遍歷:"); list.forEach(System.out::println);
輸出結果:express
map普通方式遍歷: k=a,v=a k=b,v=b k=c,v=c k=d,v=d map拉姆達表達式遍歷: k=a,v=a k=b,v=b k=c,v=c k=d,v=d list拉姆達表達式遍歷: a bb ccc dddd list雙冒號運算符遍歷: a bb ccc dddd
Lambda除了在for循環遍歷中使用外,它還能夠代替匿名的內部類。
好比下面這個例子的線程建立:api
//使用普通的方式建立 Runnable r1 = new Runnable() { @Override public void run() { System.out.println("普通方式建立!"); } }; //使用拉姆達方式建立 Runnable r2 = ()-> System.out.println("拉姆達方式建立!");
注: 這個例子中使用Lambda表達式的時候,編譯器會自動推斷:根據線程類的構造函數簽名 Runnable r { },將該 Lambda 表達式賦Runnable 接口。數組
Lambda 表達式與匿名類的區別
使用匿名類與 Lambda 表達式的一大區別在於關鍵詞的使用。對於匿名類,關鍵詞 this 解讀爲匿名類,而對於 Lambda 表達式,關鍵詞 this 解讀爲寫就 Lambda 的外部類。安全
Lambda雖然簡化了代碼的編寫,但同時也減小了可讀性。
Stream 使用一種相似用 SQL 語句從數據庫查詢數據的直觀方式來提供一種對 Java 集合運算和表達的高階抽象。Stream API能夠極大提升Java程序員的生產力,讓程序員寫出高效率、乾淨、簡潔的代碼。這種風格將要處理的元素集合看做一種流, 流在管道中傳輸, 而且能夠在管道的節點上進行處理, 好比篩選, 排序,聚合等。
Stream特性:
Stream 流操做類型:
這裏咱們依舊使用一個簡單示例來看看吧。
在開發中,咱們有時須要對一些數據進行過濾,若是是傳統的方式,咱們須要對這批數據進行遍歷過濾,會顯得比較繁瑣,若是使用steam流方式的話,那麼能夠很方便的進行處理。
首先經過普通的方式進行過濾:
List<String> list = Arrays.asList("張三", "李四", "王五", "xuwujing"); System.out.println("過濾以前:" + list); List<String> result = new ArrayList<>(); for (String str : list) { if (!"李四".equals(str)) { result.add(str); } } System.out.println("過濾以後:" + result);
使用Steam方式進行過濾:
List<String> result2 = list.stream().filter(str -> !"李四".equals(str)).collect(Collectors.toList()); System.out.println("stream 過濾以後:" + result2);
輸出結果:
過濾以前:[張三, 李四, 王五, xuwujing] 過濾以後:[張三, 王五, xuwujing] stream 過濾以後:[張三, 王五, xuwujing]
是否是很簡潔和方便呢。
其實Stream流還有更多的使用方法,filter只是其中的一角而已。那麼在這裏咱們就來學習瞭解下這些用法吧。
1.構造Stream流的方式
Stream stream = Stream.of("a", "b", "c"); String[] strArray = new String[] { "a", "b", "c" }; stream = Stream.of(strArray); stream = Arrays.stream(strArray); List<String> list = Arrays.asList(strArray); stream = list.stream();
2.Stream流的之間的轉換
注意:一個Stream流只可使用一次,這段代碼爲了簡潔而重複使用了數次,所以會拋出 stream has already been operated upon or closed 異常。
try { Stream<String> stream2 = Stream.of("a", "b", "c"); // 轉換成 Array String[] strArray1 = stream2.toArray(String[]::new); // 轉換成 Collection List<String> list1 = stream2.collect(Collectors.toList()); List<String> list2 = stream2.collect(Collectors.toCollection(ArrayList::new)); Set set1 = stream2.collect(Collectors.toSet()); Stack stack1 = stream2.collect(Collectors.toCollection(Stack::new)); // 轉換成 String String str = stream.collect(Collectors.joining()).toString(); } catch (Exception e) { e.printStackTrace(); }
3.Stream流的map使用
map方法用於映射每一個元素到對應的結果,一對一。
示例一:轉換大寫
List<String> list3 = Arrays.asList("zhangSan", "liSi", "wangWu"); System.out.println("轉換以前的數據:" + list3); List<String> list4 = list3.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println("轉換以後的數據:" + list4); // 轉換以後的數據:[ZHANGSAN, LISI,WANGWU]
示例二:轉換數據類型
List<String> list31 = Arrays.asList("1", "2", "3"); System.out.println("轉換以前的數據:" + list31); List<Integer> list41 = list31.stream().map(Integer::valueOf).collect(Collectors.toList()); System.out.println("轉換以後的數據:" + list41); // [1, 2, 3]
示例三:獲取平方
List<Integer> list5 = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }); List<Integer> list6 = list5.stream().map(n -> n * n).collect(Collectors.toList()); System.out.println("平方的數據:" + list6); // [1, 4, 9, 16, 25]
4.Stream流的filter使用
filter方法用於經過設置的條件過濾出元素。
示例二:經過與 findAny 獲得 if/else 的值
List<String> list = Arrays.asList("張三", "李四", "王五", "xuwujing"); String result3 = list.stream().filter(str -> "李四".equals(str)).findAny().orElse("找不到!"); String result4 = list.stream().filter(str -> "李二".equals(str)).findAny().orElse("找不到!"); System.out.println("stream 過濾以後 2:" + result3); System.out.println("stream 過濾以後 3:" + result4); //stream 過濾以後 2:李四 //stream 過濾以後 3:找不到!
示例三:經過與 mapToInt 計算和
List<User> lists = new ArrayList<User>(); lists.add(new User(6, "張三")); lists.add(new User(2, "李四")); lists.add(new User(3, "王五")); lists.add(new User(1, "張三")); // 計算這個list中出現 "張三" id的值 int sum = lists.stream().filter(u -> "張三".equals(u.getName())).mapToInt(u -> u.getId()).sum(); System.out.println("計算結果:" + sum); // 7
5.Stream流的flatMap使用
flatMap 方法用於映射每一個元素到對應的結果,一對多。
示例:從句子中獲得單詞
String worlds = "The way of the future"; List<String> list7 = new ArrayList<>(); list7.add(worlds); List<String> list8 = list7.stream().flatMap(str -> Stream.of(str.split(" "))) .filter(world -> world.length() > 0).collect(Collectors.toList()); System.out.println("單詞:"); list8.forEach(System.out::println); // 單詞: // The // way // of // the // future
6.Stream流的limit使用
limit 方法用於獲取指定數量的流。
示例一:獲取前n條數的數據
Random rd = new Random(); System.out.println("取到的前三條數據:"); rd.ints().limit(3).forEach(System.out::println); // 取到的前三條數據: // 1167267754 // -1164558977 // 1977868798
示例二:結合skip使用獲得須要的數據
skip表示的是扔掉前n個元素。
List<User> list9 = new ArrayList<User>(); for (int i = 1; i < 4; i++) { User user = new User(i, "pancm" + i); list9.add(user); } System.out.println("截取以前的數據:"); // 取前3條數據,可是扔掉了前面的2條,能夠理解爲拿到的數據爲 2<=i<3 (i 是數值下標) List<String> list10 = list9.stream().map(User::getName).limit(3).skip(2).collect(Collectors.toList()); System.out.println("截取以後的數據:" + list10); // 截取以前的數據: // 姓名:pancm1 // 姓名:pancm2 // 姓名:pancm3 // 截取以後的數據:[pancm3]
注:User實體類中 getName 方法會打印姓名。
7.Stream流的sort使用
sorted方法用於對流進行升序排序。
示例一:隨機取值排序
Random rd2 = new Random(); System.out.println("取到的前三條數據而後進行排序:"); rd2.ints().limit(3).sorted().forEach(System.out::println); // 取到的前三條數據而後進行排序: // -2043456377 // -1778595703 // 1013369565
示例二:優化排序
tips:先獲取在排序效率會更高!
//普通的排序取值 List<User> list11 = list9.stream().sorted((u1, u2) -> u1.getName().compareTo(u2.getName())).limit(3) .collect(Collectors.toList()); System.out.println("排序以後的數據:" + list11); //優化排序取值 List<User> list12 = list9.stream().limit(3).sorted((u1, u2) -> u1.getName().compareTo(u2.getName())) .collect(Collectors.toList()); System.out.println("優化排序以後的數據:" + list12); //排序以後的數據:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}] //優化排序以後的數據:[{"id":1,"name":"pancm1"}, {"id":2,"name":"pancm2"}, {"id":3,"name":"pancm3"}]
8.Stream流的peek使用
peek對每一個元素執行操做並返回一個新的Stream
示例:雙重操做
System.out.println("peek使用:"); Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3).peek(e -> System.out.println("轉換以前: " + e)) .map(String::toUpperCase).peek(e -> System.out.println("轉換以後: " + e)).collect(Collectors.toList()); // 轉換以前: three // 轉換以後: THREE // 轉換以前: four // 轉換以後: FOUR
9.Stream流的parallel使用
parallelStream 是流並行處理程序的代替方法。
示例:獲取空字符串的數量
List<String> strings = Arrays.asList("a", "", "c", "", "e","", " "); // 獲取空字符串的數量 long count = strings.parallelStream().filter(string -> string.isEmpty()).count(); System.out.println("空字符串的個數:"+count);
10.Stream流的max/min/distinct使用
示例一:獲得最大最小值
List<String> list13 = Arrays.asList("zhangsan","lisi","wangwu","xuwujing"); int maxLines = list13.stream().mapToInt(String::length).max().getAsInt(); int minLines = list13.stream().mapToInt(String::length).min().getAsInt(); System.out.println("最長字符的長度:" + maxLines+",最短字符的長度:"+minLines); //最長字符的長度:8,最短字符的長度:4
示例二:獲得去重以後的數據
String lines = "good good study day day up"; List<String> list14 = new ArrayList<String>(); list14.add(lines); List<String> words = list14.stream().flatMap(line -> Stream.of(line.split(" "))).filter(word -> word.length() > 0) .map(String::toLowerCase).distinct().sorted().collect(Collectors.toList()); System.out.println("去重複以後:" + words); //去重複以後:[day, good, study, up]
11.Stream流的Match使用
示例:數據是否符合
boolean all = lists.stream().allMatch(u -> u.getId() > 3); System.out.println("是否都大於3:" + all); boolean any = lists.stream().anyMatch(u -> u.getId() > 3); System.out.println("是否有一個大於3:" + any); boolean none = lists.stream().noneMatch(u -> u.getId() > 3); System.out.println("是否沒有一個大於3的:" + none); // 是否都大於3:false // 是否有一個大於3:true // 是否沒有一個大於3的:false
12.Stream流的reduce使用
reduce 主要做用是把 Stream 元素組合起來進行操做。
示例一:字符串鏈接
String concat = Stream.of("A", "B", "C", "D").reduce("", String::concat); System.out.println("字符串拼接:" + concat);
示例二:獲得最小值
double minValue = Stream.of(-4.0, 1.0, 3.0, -2.0).reduce(Double.MAX_VALUE, Double::min); System.out.println("最小值:" + minValue); //最小值:-4.0
示例三:求和
// 求和, 無起始值 int sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get(); System.out.println("有無起始值求和:" + sumValue); // 求和, 有起始值 sumValue = Stream.of(1, 2, 3, 4).reduce(1, Integer::sum); System.out.println("有起始值求和:" + sumValue); // 有無起始值求和:10 // 有起始值求和:11
示例四:過濾拼接
concat = Stream.of("a", "B", "c", "D", "e", "F").filter(x -> x.compareTo("Z") > 0).reduce("", String::concat); System.out.println("過濾和字符串鏈接:" + concat); //過濾和字符串鏈接:ace
13.Stream流的iterate使用
iterate 跟 reduce 操做很像,接受一個種子值,和一個UnaryOperator(例如 f)。 而後種子值成爲 Stream 的第一個元素,f(seed) 爲第二個,f(f(seed)) 第三個,以此類推。 在 iterate 時候管道必須有 limit 這樣的操做來限制 Stream 大小。
示例:生成一個等差隊列
System.out.println("從2開始生成一個等差隊列:"); Stream.iterate(2, n -> n + 2).limit(5).forEach(x -> System.out.print(x + " ")); // 從2開始生成一個等差隊列: // 2 4 6 8 10
14.Stream流的Supplier使用
經過實現Supplier類的方法能夠自定義流計算規則。
示例:隨機獲取兩條用戶信息
System.out.println("自定義一個流進行計算輸出:"); Stream.generate(new UserSupplier()).limit(2).forEach(u -> System.out.println(u.getId() + ", " + u.getName())); //第一次: //自定義一個流進行計算輸出: //10, pancm7 //11, pancm6 //第二次: //自定義一個流進行計算輸出: //10, pancm4 //11, pancm2 //第三次: //自定義一個流進行計算輸出: //10, pancm4 //11, pancm8 class UserSupplier implements Supplier<User> { private int index = 10; private Random random = new Random(); @Override public User get() { return new User(index++, "pancm" + random.nextInt(10)); } }
15.Stream流的groupingBy/partitioningBy使用
示例一:分組排序
System.out.println("經過id進行分組排序:"); Map<Integer, List<User>> personGroups = Stream.generate(new UserSupplier2()).limit(5) .collect(Collectors.groupingBy(User::getId)); Iterator it = personGroups.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, List<User>> persons = (Map.Entry) it.next(); System.out.println("id " + persons.getKey() + " = " + persons.getValue()); } // 經過id進行分組排序: // id 10 = [{"id":10,"name":"pancm1"}] // id 11 = [{"id":11,"name":"pancm3"}, {"id":11,"name":"pancm6"}, {"id":11,"name":"pancm4"}, {"id":11,"name":"pancm7"}] class UserSupplier2 implements Supplier<User> { private int index = 10; private Random random = new Random(); @Override public User get() { return new User(index % 2 == 0 ? index++ : index, "pancm" + random.nextInt(10)); } }
示例二:分區排序
System.out.println("經過年齡進行分區排序:"); Map<Boolean, List<User>> children = Stream.generate(new UserSupplier3()).limit(5) .collect(Collectors.partitioningBy(p -> p.getId() < 18)); System.out.println("小孩: " + children.get(true)); System.out.println("成年人: " + children.get(false)); // 經過年齡進行分區排序: // 小孩: [{"id":16,"name":"pancm7"}, {"id":17,"name":"pancm2"}] // 成年人: [{"id":18,"name":"pancm4"}, {"id":19,"name":"pancm9"}, {"id":20,"name":"pancm6"}] class UserSupplier3 implements Supplier<User> { private int index = 16; private Random random = new Random(); @Override public User get() { return new User(index++, "pancm" + random.nextInt(10)); } }
16.Stream流的summaryStatistics使用
IntSummaryStatistics 用於收集統計信息(如count、min、max、sum和average)的狀態對象。
示例:獲得最大、最小、之和以及平均數。
List<Integer> numbers = Arrays.asList(1, 5, 7, 3, 9); IntSummaryStatistics stats = numbers.stream().mapToInt((x) -> x).summaryStatistics(); System.out.println("列表中最大的數 : " + stats.getMax()); System.out.println("列表中最小的數 : " + stats.getMin()); System.out.println("全部數之和 : " + stats.getSum()); System.out.println("平均數 : " + stats.getAverage()); // 列表中最大的數 : 9 // 列表中最小的數 : 1 // 全部數之和 : 25 // 平均數 : 5.0
Stream 介紹就到這裏了,JDK1.8中的Stream流其實還有不少不少用法,更多的用法則須要你們去查看JDK1.8的API文檔了。
JDK1.8除了新增了lambda表達式、stream流以外,它還新增了全新的日期時間API。在JDK1.8以前,Java處理日期、日曆和時間的方式一直爲社區所詬病,將 java.util.Date設定爲可變類型,以及SimpleDateFormat的非線程安全使其應用很是受限。所以推出了java.time包,該包下的全部類都是不可變類型並且線程安全。
1.獲取當前的日期時間
經過靜態工廠方法now()來獲取當前時間。
//本地日期,不包括時分秒 LocalDate nowDate = LocalDate.now(); //本地日期,包括時分秒 LocalDateTime nowDateTime = LocalDateTime.now(); System.out.println("當前時間:"+nowDate); System.out.println("當前時間:"+nowDateTime); // 當前時間:2018-12-19 // 當前時間:2018-12-19T15:24:35.822
2.獲取當前的年月日時分秒
獲取時間以後,直接get獲取年月日時分秒。
//獲取當前的時間,包括毫秒 LocalDateTime ldt = LocalDateTime.now(); System.out.println("當前年:"+ldt.getYear()); //2018 System.out.println("當前年份天數:"+ldt.getDayOfYear());//172 System.out.println("當前月:"+ldt.getMonthValue()); System.out.println("當前時:"+ldt.getHour()); System.out.println("當前分:"+ldt.getMinute()); System.out.println("當前時間:"+ldt.toString()); // 當前年:2018 // 當前年份天數:353 // 當前月:12 // 當前時:15 // 當前分:24 // 當前時間:2018-12-19T15:24:35.833
3.格式化時間
格式時間格式須要用到DateTimeFormatter類。
LocalDateTime ldt = LocalDateTime.now(); System.out.println("格式化時間: "+ ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))); //格式化時間:2018-12-19 15:37:47.119
4.時間增減
在指定的時間進行增長/減小年月日時分秒。
LocalDateTime ldt = LocalDateTime.now(); System.out.println("後5天時間:"+ldt.plusDays(5)); System.out.println("前5天時間並格式化:"+ldt.minusDays(5).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))); //2018-06-16 System.out.println("前一個月的時間:"+ldt2.minusMonths(1).format(DateTimeFormatter.ofPattern("yyyyMM"))); //2018-06-16 System.out.println("後一個月的時間:"+ldt2.plusMonths(1)); //2018-06-16 System.out.println("指定2099年的當前時間:"+ldt.withYear(2099)); //2099-06-21T15:07:39.506 // 後5天時間:2018-12-24T15:50:37.508 // 前5天時間並格式化:2018-12-14 // 前一個月的時間:201712 // 後一個月的時間:2018-02-04T09:19:29.499 // 指定2099年的當前時間:2099-12-19T15:50:37.508
5.建立指定時間
經過指定年月日來建立。
LocalDate ld3=LocalDate.of(2017, Month.NOVEMBER, 17); LocalDate ld4=LocalDate.of(2018, 02, 11);
6.時間相差比較
比較相差的年月日時分秒。
示例一: 具體相差的年月日
LocalDate ld=LocalDate.parse("2017-11-17"); LocalDate ld2=LocalDate.parse("2018-01-05"); Period p=Period.between(ld, ld2); System.out.println("相差年: "+p.getYears()+" 相差月 :"+p.getMonths() +" 相差天:"+p.getDays()); // 相差年: 0 相差月 :1 相差天:19
注:這裏的月份是不知足一年,天數是不知足一個月的。這裏實際相差的是1月19天,也就是49天。
示例二:相差總數的時間
ChronoUnit 日期週期單位的標準集合。
LocalDate startDate = LocalDate.of(2017, 11, 17); LocalDate endDate = LocalDate.of(2018, 01, 05); System.out.println("相差月份:"+ChronoUnit.MONTHS.between(startDate, endDate)); System.out.println("兩月之間的相差的天數 : " + ChronoUnit.DAYS.between(startDate, endDate)); // 相差月份:1 // 兩天之間的差在天數 : 49
注:ChronoUnit也能夠計算相差時分秒。
示例三:精度時間相差
Duration 這個類以秒和納秒爲單位建模時間的數量或數量。
Instant inst1 = Instant.now(); System.out.println("當前時間戳 : " + inst1); Instant inst2 = inst1.plus(Duration.ofSeconds(10)); System.out.println("增長以後的時間 : " + inst2); System.out.println("相差毫秒 : " + Duration.between(inst1, inst2).toMillis()); System.out.println("相毫秒 : " + Duration.between(inst1, inst2).getSeconds()); // 當前時間戳 : 2018-12-19T08:14:21.675Z // 增長以後的時間 : 2018-12-19T08:14:31.675Z // 相差毫秒 : 10000 // 相毫秒 : 10
示例四:時間大小比較
LocalDateTime ldt4 = LocalDateTime.now(); LocalDateTime ldt5 = ldt4.plusMinutes(10); System.out.println("當前時間是否大於:"+ldt4.isAfter(ldt5)); System.out.println("當前時間是否小於"+ldt4.isBefore(ldt5)); // false // true
7.時區時間計算
獲得其餘時區的時間。
示例一:經過Clock時鐘類獲取計算
Clock時鐘類用於獲取當時的時間戳,或當前時區下的日期時間信息。
Clock clock = Clock.systemUTC(); System.out.println("當前時間戳 : " + clock.millis()); Clock clock2 = Clock.system(ZoneId.of("Asia/Shanghai")); System.out.println("亞洲上海此時的時間戳:"+clock2.millis()); Clock clock3 = Clock.system(ZoneId.of("America/New_York")); System.out.println("美國紐約此時的時間戳:"+clock3.millis()); // 當前時間戳 : 1545209277657 // 亞洲上海此時的時間戳:1545209277657 // 美國紐約此時的時間戳:1545209277658
示例二:經過ZonedDateTime類和ZoneId
ZoneId zoneId= ZoneId.of("America/New_York"); ZonedDateTime dateTime=ZonedDateTime.now(zoneId); System.out.println("美國紐約此時的時間 : " + dateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))); System.out.println("美國紐約此時的時間 和時區: " + dateTime); // 美國紐約此時的時間 : 2018-12-19 03:52:22.494 // 美國紐約此時的時間 和時區: 2018-12-19T03:52:22.494-05:00[America/New_York]
Java 8日期時間API總結:
參考:
http://blog.oneapm.com/apm-tech/226.html
https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/
http://www.importnew.com/15637.html
分享一首很是帶感的電音!你若想作,那麼就去作吧!
java-study是本人在學習Java過程當中記錄的一些代碼,也包括以前博文中使用的代碼。若是感受不錯,但願順手給個start,固然若是有不足,也但願提出。
github地址: https://github.com/xuwujing/java-study
原創不易,若是感受不錯,但願給個推薦!您的支持是我寫做的最大動力! 版權聲明: 做者:虛無境 博客園出處:http://www.cnblogs.com/xuwujing CSDN出處:http://blog.csdn.net/qazwsxpcm 我的博客出處:http://www.panchengming.com