zoukankan      html  css  js  c++  java
  • Java基础学习08--JDK1.8特性

    1.Lambda表达式

    Lambda表达式时特殊的匿名内部类,语法更简洁。它允许把函数作为一个方法的参数(函数作为方法参数传递),将代码像数据一样传递。

     1 package com.example.jdk8;
     2 
     3 import java.util.Comparator;
     4 import java.util.TreeSet;
     5 
     6 public class demo01 {
     7     // Lambda表达式
     8     public static void main(String[] args) {
     9         // 1.线程
    10         Runnable runnable = new Runnable() {
    11 
    12             @Override
    13             public void run() {
    14                 System.out.println("使用匿名内部类");
    15             }
    16         };
    17         new Thread(runnable).start();
    18 
    19         Runnable runnable1 = () -> System.out.println("使用Lambda表达式");
    20         new Thread(runnable1).start();
    21 
    22         // 2.比较器
    23         Comparator<String> com = new Comparator<String>() {
    24 
    25             @Override
    26             public int compare(String o1, String o2) {
    27                 return o1.length() - o2.length();
    28             }
    29         };
    30 
    31         TreeSet<String> treeSet = new TreeSet<>(com);
    32 
    33         TreeSet<String> treeSet2 = new TreeSet<String>((o1, o2) -> o1.length() - o2.length());
    34     }
    35 }

    2.函数式接口

    如果一个接口只有一个抽象方法,则该接口称为函数式接口,只有函数式接口可以使用Lambda表达式。

     1 package com.example.jdk8;
     2 
     3 import java.util.Comparator;
     4 import java.util.TreeSet;
     5 import java.util.function.Consumer;
     6 import java.util.function.Function;
     7 import java.util.function.Predicate;
     8 import java.util.function.Supplier;
     9 
    10 public class demo02 {
    11 
    12     public static void main(String[] args) {
    13         Usb mouse = new Usb() {
    14 
    15             @Override
    16             public void service() {
    17                 // TODO Auto-generated method stub
    18                 System.out.println("默认实现接口");
    19             }
    20         };
    21         mouse.service();
    22 
    23         Usb fan = () -> System.out.println("Lambda表达式实现接口");
    24         fan.service();
    25 
    26         // 常见函数式接口
    27 
    28         // 1.消费型,参数T,返回值void
    29         Consumer<Integer> consumer = (i) -> System.out.println("Lambda表达式实现接口");
    30 
    31         // 2.供给型,参数无,返回T
    32         Supplier<Integer> supplier = () -> {
    33             return Integer.valueOf(100);
    34         };
    35 
    36         // 3.函数型,参数T,返回值R
    37         Function<Integer, String> function = (i) -> {
    38             return i.toString();
    39         };
    40 
    41         // 4.断言,输入T,返回boolean
    42         Predicate<Integer> predicate = (i) -> i > 10;
    43     }
    44 }

    3.方法引用

    对象::实例方法

    类::静态方法

    类::实例方法

    类::new

     1 package com.example.jdk8;
     2 
     3 import java.util.Comparator;
     4 import java.util.function.Consumer;
     5 import java.util.function.Function;
     6 import java.util.function.Supplier;
     7 
     8 public class demo03 {
     9     public static void main(String[] args) {
    10         // 1.对象::实例方法
    11         Consumer<String> consumer = s -> System.out.println(s);
    12         consumer.accept("hello");
    13 
    14         // println()是一个输入参数,无返回值的方法
    15         // consumer2是一个输入参数,无返回值的方法
    16         // 这两个方法的形式一致,就可以使用"方法引用"的简写形式
    17         Consumer<String> consumer2 = System.out::println;
    18         consumer2.accept("world");
    19 
    20         // 2.类::静态方法
    21         Comparator<Integer> com = (o1, o2) -> Integer.compare(o1, o2);
    22         Comparator<Integer> com2 = Integer::compare;
    23 
    24         // 3.类::实例方法
    25         Function<Employee, String> function = e -> e.getName();
    26         Function<Employee, String> function2 = Employee::getName;
    27 
    28         // 4.类::new
    29         Supplier<Employee> supplier = () -> new Employee();
    30         Supplier<Employee> supplier2 = Employee::new;
    31     }
    32 }

    4.Stream流

    流中保存对集合或数组数据的操作。

    (1)Stream自己不会存储元素。

    (2)Stream不会改变源对象,相反,他们会返回一个持有结果的新Stream。

    (3)Stream操作时延迟执行的。

    使用步骤:创建,中间操作,终止操作。

    4.1创建

     1 package com.example.jdk8;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Arrays;
     5 import java.util.Random;
     6 import java.util.stream.IntStream;
     7 import java.util.stream.Stream;
     8 
     9 public class demo04 {
    10 
    11     public static void main(String[] args) {
    12         // 创建Stream
    13         // (1)Collection对象中的stream(方法)和parallelStream()方法创建流
    14         ArrayList<String> arrayList = new ArrayList<>();
    15         arrayList.add("1");
    16         arrayList.add("2");
    17         arrayList.add("3");
    18 
    19         // 串行流
    20         Stream stream = arrayList.stream();
    21         stream.forEach(s -> System.out.println(s));
    22 
    23         // 并行流,使用多线程,打印顺序可能不固定
    24         Stream stream1 = arrayList.parallelStream();
    25         stream1.forEach(System.out::println);
    26 
    27         // (2)Array工具类的stram()方法
    28         String[] arr = { "aaa", "bbb", "ccc" };
    29         Stream<String> stream2 = Arrays.stream(arr);
    30         stream2.forEach(System.out::println);
    31 
    32         // (3)stream接口中的of方法 iterate、generate
    33         Stream<Integer> stream3 = Stream.of(10, 20, 30);
    34         stream3.forEach(System.out::println);
    35 
    36         // 迭代流
    37         System.out.println("--------迭代流-----------");
    38         Stream<Integer> iterate = Stream.iterate(0, x -> x + 2);
    39         iterate.limit(10).forEach(System.out::println);
    40         System.out.println("--------生成流-----------");
    41         Stream<Integer> generate = Stream.generate(() -> new Random().nextInt(100));
    42         generate.limit(10).forEach(System.out::println);
    43 
    44         // (4)IntStream,LongStream,DoubleStream的of,range,rangeClosed
    45         IntStream stream4 = IntStream.of(100, 200, 300);
    46         stream4.forEach(System.out::println);
    47     }
    48 }

    4.2中间操作

     1 package com.example.jdk8;
     2 
     3 import java.util.ArrayList;
     4 
     5 public class demo05 {
     6     public static void main(String[] args) {
     7         ArrayList<Employee> list = new ArrayList<>();
     8         list.add(new Employee("1", 1));
     9         list.add(new Employee("2", 2));
    10         list.add(new Employee("3", 3));
    11         list.add(new Employee("4", 4));
    12         list.add(new Employee("5", 5));
    13         list.add(new Employee("4", 4));
    14         // 中间操作:
    15         // 1 filter过滤
    16         System.out.println("-----------filter--------------");
    17         list.stream().filter(e -> e.getAmount() > 3).forEach(System.out::println);
    18 
    19         // 2 limit限制
    20         System.out.println("-----------limit--------------");
    21         list.stream().limit(2).forEach(System.out::println);
    22 
    23         // 3 skip跳过
    24         System.out.println("-----------skip--------------");
    25         list.stream().skip(2).forEach(System.out::println);
    26 
    27         // 4 distinct去重
    28         // 需要override hashcode()和equals()
    29         System.out.println("-----------distinct--------------");
    30         list.stream().distinct().forEach(System.out::println);
    31 
    32         // 5 sorted排序
    33         System.out.println("-----------sorted--------------");
    34         list.stream().sorted((o1, o2) -> Integer.compare(o1.getAmount(), o2.getAmount())).forEach(System.out::println);
    35 
    36         // 中间操作2 map
    37         System.out.println("-----------map--------------");
    38         list.stream().map(e -> e.getName()).forEach(System.out::println);
    39 
    40         // 中间操作3 parallel 采用多线程
    41         System.out.println("-----------parallel--------------");
    42         list.parallelStream().forEach(System.out::println);
    43     }
    44 }

    4.3终止操作

    forEach、min、max、count、reduce、collect

     1 package com.example.jdk8;
     2 
     3 import java.util.ArrayList;
     4 import java.util.List;
     5 import java.util.Optional;
     6 import java.util.stream.Collectors;
     7 
     8 public class demo06 {
     9 
    10     public static void main(String[] args) {
    11         ArrayList<Employee> list = new ArrayList<>();
    12         list.add(new Employee("1", 1));
    13         list.add(new Employee("2", 2));
    14         list.add(new Employee("3", 3));
    15         list.add(new Employee("4", 4));
    16         list.add(new Employee("5", 5));
    17 
    18         // forEach 终止操作
    19         System.out.println("--------------forEach--------------");
    20         list.stream().filter(e -> e.getAmount() > 2).forEach(System.out::println);
    21 
    22         // min/max/count 终止操作
    23         System.out.println("--------------min--------------");
    24         Optional<Employee> min = list.stream().min((e1, e2) -> Integer.compare(e1.getAmount(), e2.getAmount()));
    25         System.out.println(min.get());
    26 
    27         // reduce 终止操作
    28         System.out.println("--------------reduce--------------");
    29         Optional<Integer> sum = list.stream().map(e -> e.getAmount()).reduce((x, y) -> x + y);
    30         System.out.println(sum.get());
    31 
    32         // collect 终止操作
    33         System.out.println("--------------collect--------------");
    34         List<String> lists = list.stream().map(e -> e.getName()).collect(Collectors.toList());
    35         for (String s : lists) {
    36             System.out.println(s);
    37         }
    38     }
    39 }

    5.新日期时间API

    SimpleDateFormat类是线程不安全的,DateTimeFormatter类是JDK1.8新增的,线程安全。

     1 package com.example.jdk8;
     2 
     3 import java.time.Duration;
     4 import java.time.Instant;
     5 import java.time.LocalDateTime;
     6 import java.time.ZoneId;
     7 import java.time.format.DateTimeFormatter;
     8 import java.util.Date;
     9 import java.util.Set;
    10 
    11 import org.springframework.format.annotation.DateTimeFormat;
    12 
    13 public class demo07 {
    14     public static void main(String[] args) {
    15         // LocalDate LocalTime LocalDateTime
    16         // 创建日期时间
    17         LocalDateTime ldt = LocalDateTime.now();
    18         LocalDateTime ldt2 = LocalDateTime.of(2021, 2, 1, 15, 54);
    19 
    20         System.out.println(ldt);
    21         System.out.println(ldt2.getMonth());
    22 
    23         // 2增加/减少时间
    24         LocalDateTime plusDays = ldt2.plusDays(2);
    25         System.out.println(plusDays);
    26 
    27         // Instant 时间戳
    28         Instant instant = Instant.now();
    29         // Instant.ofEpochMilli(1612166319268L);
    30 
    31         System.out.println(instant);
    32         System.out.println(instant.toEpochMilli());
    33 
    34         Instant instant2 = instant.plusSeconds(10);
    35         System.out.println(Duration.between(instant, instant2).toMillis());
    36 
    37         // ZoneId时区
    38         Set<String> sets = ZoneId.getAvailableZoneIds();
    39         for (String s : sets) {
    40             System.out.println(s);
    41         }
    42         System.out.println("当前时区");
    43         System.out.println(ZoneId.systemDefault());// Asia/Shanghai
    44 
    45         // Date Instant LocalDateTime 几种日期类型转换
    46         // Date -> Instant -> LocalDateTime
    47         Date date = new Date();
    48         Instant inst = date.toInstant();
    49         LocalDateTime ldt3 = LocalDateTime.ofInstant(inst, ZoneId.systemDefault());
    50         System.out.println(ldt3);
    51 
    52         // LocalDateTime -> Instant -> Date
    53         Instant inst2 = ldt3.atZone(ZoneId.systemDefault()).toInstant();
    54         Date from = date.from(inst2);
    55         System.out.println(from);
    56 
    57         // DateTimeFormat
    58         DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    59         // 时间格式化成字符串
    60         System.out.println(dtf.format(LocalDateTime.now()));
    61 
    62         // 字符串转换为时间
    63         LocalDateTime ldt4 = LocalDateTime.parse("2021-02-01 16:10:02", dtf);
    64         System.out.println(ldt4);
    65     }
    66 }
  • 相关阅读:
    接口开发
    操作Excel
    操作mongodb
    sys模块
    操作redis
    操作数据库
    日志生成、发送邮件
    Codeforces Round #487 (Div. 2)
    bitset学习
    Training for 分块&莫队
  • 原文地址:https://www.cnblogs.com/asenyang/p/14357190.html
Copyright © 2011-2022 走看看