Java番外篇2——jdk8新特性
生活随笔
收集整理的這篇文章主要介紹了
Java番外篇2——jdk8新特性
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Java番外篇2——jdk8新特性
1、Lambda
1.1、無參無返回值
public class Test {interface Print{void print();}public static void main(String[] args) { // Print print=new Print() { // @Override // public void print() { // System.out.println("hello word!"); // } // };Print print=()-> System.out.println("hello word!");print.print();} }1.2、一個(gè)參數(shù)無返回值
public class Test {interface Print{void print(String str);}public static void main(String[] args) { // Print print=new Print() { // @Override // public void print(String str) { // System.out.println("hello word! "+str); // } // };Print print=str-> System.out.println("hello word! "+str);print.print("ruoye");} }1.3、多個(gè)參數(shù)無返回值
public class Test {interface Print{void print(String str,String str1);}public static void main(String[] args) { // Print print=new Print() { // @Override // public void print(String str,String str1); { // System.out.println("hello word! "+str+str1); // } // };Print print=(str,str1)-> System.out.println("hello word! "+str+str1);print.print("ruoye","yoya");} }1.4、多個(gè)參數(shù)有返回值(單句)
public class Test {interface Print{String print(String str,String str1);}public static void main(String[] args) {Print print=(str,str1)-> str+str1;System.out.println(print.print("ruoye", "yoya"));} }1.4、多個(gè)參數(shù)有返回值(多句)
public class Test {interface Print{String print(String str,String str1);}public static void main(String[] args) {Print print=(str,str1)-> {System.out.println("hello word! "+str+str1);return str+str1;};System.out.println(print.print("ruoye", "yoya"));} }2、函數(shù)式接口(@FunctionalInterface)
- 該注解只能標(biāo)記在"有且僅有一個(gè)抽象方法"的接口上
- JDK8接口中可以定義靜態(tài)方法和默認(rèn)方法(方法默認(rèn)實(shí)現(xiàn)default),都不算是抽象方法
3、接口調(diào)整
方便接口擴(kuò)展
jdk8之前接口只能有靜態(tài)常量和抽象方法
jdk8后接口可以有默認(rèn)方法和靜態(tài)方法
public interface Print{public static void aaa(){System.out.println("aaa");}public default void bbb(){System.out.println("bbb");}String print(String str,String str1); }4、方法引用
::5、Stream(流水線)
- 集合遍歷有弊端
- 篩選
- 切片
- 映射
- 查找
- 去重
- 統(tǒng)計(jì)
- 匹配
- 歸約
特性
-
Stream只能操作一次
-
Stream方法返回的是新的流
-
Stream不調(diào)用終結(jié)方法,中間的操作不會(huì)執(zhí)行
5.1、Stream的獲取
public class Test {public static void main(String[] args) {//集合List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");Stream<String> stream = strings.stream();//數(shù)組String[] strings1={"zhangsan", "lisi", "wangwu", "zhaoliu"};Stream<String> stream1 = Stream.of(strings1);//map可以通過獲取鍵集合,值集合,從而獲得流} }5.2、常用方法
| count | 統(tǒng)計(jì)個(gè)數(shù) | long | 終結(jié) |
| forEach | 逐一處理 | void | 終結(jié) |
| filter | 過濾 | Stream | 函數(shù)拼接 |
| limit | 取用前幾個(gè) | Stream | 函數(shù)拼接 |
| skip | 跳過前幾個(gè) | Stream | 函數(shù)拼接 |
| map | 映射 | Stream | 函數(shù)拼接 |
| concat | 組合 | Stream | 函數(shù)拼接 |
5.3、forEach
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");strings.stream().forEach(System.out::println);} }5.4、count
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");System.out.println(strings.stream().count());} }5.5、filter
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");strings.stream().filter(s -> s.startsWith("z")).forEach(System.out::println);} }5.6、limit
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");strings.stream().limit(1).forEach(System.out::println);} }5.7、skip
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");strings.stream().skip(1).forEach(System.out::println);} }5.8、map
完成數(shù)據(jù)轉(zhuǎn)換、處理
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");strings.stream().map(s->s+="yoya").forEach(System.out::println);} }5.9、sorted
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu");strings.stream().sorted().forEach(System.out::println);} }5.10、distinct
Stream流中的distinct方法對(duì)于基本數(shù)據(jù)類型是可以直接出重的,但是對(duì)于自定義類型,需要重寫hashCode和equals方法來移除重復(fù)元素
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");strings.stream().distinct().forEach(System.out::println);} }5.11、match
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");System.out.println(strings.stream().anyMatch(s -> s.startsWith("z")));} } public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");System.out.println(strings.stream().allMatch(s -> s.startsWith("z")));} } public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");System.out.println(strings.stream().noneMatch(s -> s.startsWith("z")));} }5.12、find
findfirst返回第一個(gè)元素
findany返回隨機(jī)一個(gè)元素
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");Optional<String> z = strings.stream().filter(s -> s.startsWith("z")).findAny();System.out.println(z.get());} }5.13、max,min
public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");Optional<String> max = strings.stream().max((s1, s2) -> {return s1.compareTo(s2);});System.out.println(max.get());} } public class Test {public static void main(String[] args) {List<String> strings = Arrays.asList("zhangsan", "lisi", "wangwu", "zhaoliu","zhangsan");Optional<String> max = strings.stream().min((s1, s2) -> {return s1.compareTo(s2);});System.out.println(max.get());} }5.14、reduce
歸約
public class Test {public static void main(String[] args) {Integer reduce = Stream.of(1, 2, 3, 4, 5).reduce(0, (a, b) -> {return a + b;});System.out.println(reduce);} }5.15、mapToInt
轉(zhuǎn)為int
public class Test {public static void main(String[] args) {Integer[] integers={1, 2, 3, 4, 5};Stream.of(integers).mapToInt(Integer::intValue).forEach(System.out::println);} }5.16、concat
合并流
public class Test {public static void main(String[] args) {Integer[] integers={1, 2, 3, 4, 5};Integer[] integers1={6,7,8,9,10};Stream<Integer> concat = Stream.concat(Stream.of(integers), Stream.of(integers1));concat.mapToInt(Integer::intValue).forEach(System.out::println);} }5.17、結(jié)果收集
public class Test {public static void main(String[] args) {Integer[] integers={1, 2, 3, 4, 5};Integer[] integers1={6,7,8,9,10};Stream<Integer> concat = Stream.concat(Stream.of(integers), Stream.of(integers1));List<Integer> collect = concat.collect(Collectors.toList());System.out.println(collect);} } public class Test {public static void main(String[] args) {Integer[] integers={1, 2, 3, 4, 5};Integer[] integers1={6,7,8,9,10};Stream<Integer> concat = Stream.concat(Stream.of(integers), Stream.of(integers1));List<Integer> collect = concat.collect(Collectors.toCollection(ArrayList::new));System.out.println(collect);} } public class Test {public static void main(String[] args) {Integer[] integers={1, 2, 3, 4, 5};Integer[] integers1={6,7,8,9,10};Stream<Integer> concat = Stream.concat(Stream.of(integers), Stream.of(integers1));Integer[] integers2 = concat.toArray(Integer[]::new);System.out.println(Arrays.toString(integers2));} }5.19、聚合
public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "wangwu", false);Person person3 = new Person(4, "zhaoliu", true);Person person4 = new Person(5, "qianqi", true);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);Optional<Person> collect = person.collect(Collectors.maxBy((p1, p2) -> {return p1.getId() - p2.getId();}));System.out.println(collect.get());} } public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "wangwu", false);Person person3 = new Person(4, "zhaoliu", true);Person person4 = new Person(5, "qianqi", true);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);Integer collect = person.collect(Collectors.summingInt(p -> p.getId()));System.out.println(collect);} } public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "wangwu", false);Person person3 = new Person(4, "zhaoliu", true);Person person4 = new Person(5, "qianqi", true);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);Double collect = person.collect(Collectors.averagingInt(Person::getId));System.out.println(collect);} } public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "wangwu", false);Person person3 = new Person(4, "zhaoliu", true);Person person4 = new Person(5, "qianqi", true);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);Long collect = person.collect(Collectors.counting());System.out.println(collect);} }5.20、分組
public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "zhangsan", false);Person person3 = new Person(4, "lisi", true);Person person4 = new Person(5, "zhangsan", true); // Stream<Person> person = Stream.of(person0, person1, person2, person3, person4); // Map<String, List<Person>> collect = person // .collect(Collectors.groupingBy(person5 -> person5.getName())); // System.out.println(collect);// Stream<Person> person = Stream.of(person0, person1, person2, person3, person4); // Map<String, List<Person>> collect = person // .collect(Collectors.groupingBy(person5 -> person5.isGender()?"男":"女")); // System.out.println(collect);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);Map<String, Map<String, List<Person>>> collect = person.collect(Collectors.groupingBy(person5 -> person5.getName(), Collectors.groupingBy(person5 -> person5.isGender() ? "男" : "女")));System.out.println(collect);} }5.21、分區(qū)
public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "zhangsan", false);Person person3 = new Person(4, "lisi", true);Person person4 = new Person(5, "zhangsan", true);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);Map<Boolean, List<Person>> collect = person.collect(Collectors.partitioningBy(person5 -> person5.isGender()));System.out.println(collect);} }5.22、joining
public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "zhangsan", false);Person person3 = new Person(4, "lisi", true);Person person4 = new Person(5, "zhangsan", true);// Stream<Person> person = Stream.of(person0, person1, person2, person3, person4); // String collect = person // .map(person5 -> person5.getName()) // .collect(Collectors.joining()); // System.out.println(collect); // // Stream<Person> person = Stream.of(person0, person1, person2, person3, person4); // String collect = person // .map(person5 -> person5.getName()) // .collect(Collectors.joining("_")); // System.out.println(collect);Stream<Person> person = Stream.of(person0, person1, person2, person3, person4);String collect = person.map(person5 -> person5.getName()).collect(Collectors.joining("_","###","$$$"));System.out.println(collect);} }5.23、并行流
public class Test {public static void main(String[] args) {Person person0 = new Person(1, "zhangsan", true);Person person1 = new Person(2, "lisi", true);Person person2 = new Person(3, "zhangsan", false);Person person3 = new Person(4, "lisi", true);Person person4 = new Person(5, "zhangsan", true);Stream<Person> person01 = Stream.of(person0, person1, person2, person3, person4).parallel();person01.map(s->{System.out.println(Thread.currentThread()+"==="+s);return s;}).forEach(System.out::println);} }并行流出現(xiàn)問題可嘗試使用同步代碼塊
6、日期
- 設(shè)計(jì)不合理,在java.util和java.sql的包中都有日期類,java.util.Date同時(shí)包含日期和時(shí)間的,而 java.sql.Date僅僅包含日期,此外用于格式化和解析的類在java.text包下
- 非線程安全,java.util.Date是非線程安全的,所有的日期類都是可變的,這是java日期類最大的問 題之一
- 時(shí)區(qū)處理麻煩,日期類并不提供國(guó)際化,沒有時(shí)區(qū)支持
JDK 8中增加了一套全新的日期時(shí)間API,這套API設(shè)計(jì)合理,是線程安全(每次都返回新對(duì)象)的,新的日期及時(shí)間API位于java.time包
- LocalDate :表示日期,包含年月日,格式為 2019-10-16
- LocalTime :表示時(shí)間,包含時(shí)分秒,格式為 16:38:54.158549300
- LocalDateTime :表示日期時(shí)間,包含年月日,時(shí)分秒,格式為 2018-09-06T15:33:56.750
- DateTimeFormatter :日期時(shí)間格式化類
- Instant:時(shí)間戳,表示一個(gè)特定的時(shí)間瞬間
- Duration:用于計(jì)算2個(gè)時(shí)間(LocalTime,時(shí)分秒)的距離
- Period:用于計(jì)算2個(gè)日期(LocalDate,年月日)的距離
- ZonedDateTime :包含時(shí)區(qū)的時(shí)間
6.1、LocalDate
public class Test {public static void main(String[] args) {//指定日期創(chuàng)建LocalDate localDate=LocalDate.of(2020,10,19);System.out.println(localDate);//當(dāng)前日期創(chuàng)建System.out.println(LocalDate.now());//更改日期LocalDate localDate1 = localDate.withMonth(11);System.out.println(localDate1);//日期增減(plus,minus)LocalDate localDate2 = localDate1.plusDays(1);System.out.println(localDate2);//日期比較System.out.println(localDate.isAfter(localDate1));System.out.println(localDate.isBefore(localDate1));} }6.2、LocalTime
public class Test {public static void main(String[] args) {//指定時(shí)間創(chuàng)建LocalTime localTime=LocalTime.of(10,19,0,123);System.out.println(localTime);//當(dāng)前時(shí)間創(chuàng)建System.out.println(LocalTime.now());//時(shí)間更改LocalTime localTime1 = localTime.withHour(11);System.out.println(localTime1);//時(shí)間增減(plus,minus)LocalTime localTime2 = localTime1.plusHours(1);System.out.println(localTime2);//時(shí)間比較同上} }6.3、LocalDateTime
public class Test {public static void main(String[] args) {LocalDate now = LocalDate.now();LocalTime now1 = LocalTime.now();LocalDateTime now2 = LocalDateTime.now();System.out.println(LocalDateTime.of(now,now1));System.out.println(now2);//同樣有設(shè)置、增減、比較} }6.4、DateTimeFormatter
日期時(shí)間格式化與解析
public class Test {public static void main(String[] args) {LocalDateTime now = LocalDateTime.now();DateTimeFormatter dateTimeFormatter=DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");System.out.println(dateTimeFormatter.format(now));String str="2021-07-16 11:03:00";LocalDateTime parse = LocalDateTime.parse(str, dateTimeFormatter);System.out.println(parse);} }6.5、Instant
public class Test {public static void main(String[] args) {Instant instant=Instant.now();System.out.println(instant.getNano());} }6.6、Duration、Period
Duration:時(shí)間差
Period:日期差
public class Test {public static void main(String[] args) {Duration duration = Duration.between(LocalTime.now(), LocalTime.of(12, 0, 0, 0));System.out.println(duration.toHours());System.out.println(duration.toMinutes());System.out.println(duration.toMillis());} } public class Test {public static void main(String[] args) {Period period = Period.between(LocalDate.now(), LocalDate.of(2022, 5, 2));System.out.println(period.getDays());System.out.println(period.getMonths());System.out.println(period.getYears());} }6.7、時(shí)區(qū)
public class Test {public static void main(String[] args) {//所有時(shí)區(qū)for (String availableZoneId : ZoneId.getAvailableZoneIds()) {System.out.println(availableZoneId);}//獲取標(biāo)準(zhǔn)時(shí)間ZonedDateTime zonedDateTime=ZonedDateTime.now(Clock.systemUTC());System.out.println(zonedDateTime);//獲取默認(rèn)時(shí)區(qū)時(shí)間ZonedDateTime zonedDateTime1=ZonedDateTime.now();System.out.println(zonedDateTime1);//獲取指定時(shí)區(qū)世家ZonedDateTime zonedDateTime2=ZonedDateTime.now(ZoneId.of("America/Cuiaba"));System.out.println(zonedDateTime2);} }7、@Repeatable
允許重復(fù)注解
8、@Target屬性
ElementType.TYPE_PARAMETER:允許注解寫在聲明語句中
ElementType.TYPE_USE:任何定義的地方都可以用
總結(jié)
以上是生活随笔為你收集整理的Java番外篇2——jdk8新特性的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python 数据增强 -- PIL模块
- 下一篇: java string... 参数_Ja