首页 > 基础资料 博客日记
24_Java8
2023-08-11 19:53:51基础资料围观208次
这篇文章介绍了24_Java8,分享给大家做个参考,收藏Java资料网收获更多编程知识
目录
Java8
一. Java8概述
- Java8(又称JDK1.8)是Java语言开发的一个主要版本. Oracle公司于2014年3月18日发布Java8
- 支持Lambda表达式
- 函数式接口
- 新的Stream API
- 新的日期 API
- 其他特性
二. Lambda表达式
- Lambda表达式: 特殊的匿名内部类, 语法更简洁
- Lambda表达式允许把函数作为一个方法的参数(函数作为方法的参数传递), 将代码像数据一样传递
- 基本语法
- <函数式接口> <变量名> = (参数1, 参数2...) -> {//方法体};
- Lambda引入了新的操作符: -> (箭头操作符), -> 将表达式分成两部分
- 左侧: (参数1, 参数2...)表示参数列表
- 右侧: {}内部是方法体
- 注意事项
- 形参列表的数据类型会自动推断
- 如果形参列表为空, 只需保留()
- 如果形参只有一个, ()可以省略, 只需要参数的名称即可
- 如果执行语句只有一句, 且无返回值, {}可以省略, 若有返回值, 则若想省去{}, 则必须同时省略return, 且执行语句也保证只有一句
- Lambda不会生成一个单独的内部类文件
public class TestLambda {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//1. 匿名内部类</span>
<span class="hljs-type">Runnable</span> <span class="hljs-variable">runnable1</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Runnable</span>() {
<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">()</span> {
System.out.println(<span class="hljs-string">"子线程1运行了..."</span>);
}
};
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Thread</span>(runnable1).start();
<span class="hljs-comment">//2. Lambda表达式</span>
<span class="hljs-comment">//2.1 将匿名内部类简化为Lambda表达式</span>
<span class="hljs-type">Runnable</span> <span class="hljs-variable">runnable2</span> <span class="hljs-operator">=</span> () -> System.out.println(<span class="hljs-string">"子线程2运行了..."</span>);
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Thread</span>(runnable2).start();
<span class="hljs-comment">//2.2 把Lambda表达式作为参数传递</span>
<span class="hljs-keyword">new</span> <span class="hljs-title class_">Thread</span>(() -> System.out.println(<span class="hljs-string">"子线程3运行了..."</span>)).start();
<span class="hljs-comment">//3. Lambda表达式</span>
<span class="hljs-comment">//匿名内部类</span>
Comparator<String> comparator1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Comparator</span><String>() {
<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-type">int</span> <span class="hljs-title function_">compare</span><span class="hljs-params">(String o1, String o2)</span> {
<span class="hljs-keyword">return</span> o1.length() - o2.length();
}
};
TreeSet<String> treeSet1 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TreeSet</span><>(comparator1);
<span class="hljs-comment">//3.1 将匿名内部类简化为Lambda表达式</span>
Comparator<String> comparator2 = (o1, o2) -> o1.length() - o2.length();
TreeSet<String> treeSet2 = <span class="hljs-keyword">new</span> <span class="hljs-title class_">TreeSet</span><>(comparator2);
}
}
三. 函数式接口
- 如果一个接口只有一个抽象方法, 则该接口称之为函数式接口, 函数式接口可以使用Lambda表达式, Lambda表达式会被匹配到这个抽象方法上
- @FunctionalInterface 注解检测接口是否符合函数式接口
//函数式接口: 接口中只有一个抽象方法
@FunctionalInterface //验证是否是函数式接口
public interface Usb {
<span class="hljs-keyword">void</span> <span class="hljs-title function_">service</span><span class="hljs-params">()</span>;
}
public class Demo01 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//1. 匿名内部类</span>
<span class="hljs-type">Usb</span> <span class="hljs-variable">mouse</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Usb</span>() {
<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">service</span><span class="hljs-params">()</span> {
System.out.println(<span class="hljs-string">"鼠标开始工作了..."</span>);
}
};
run(mouse);
<span class="hljs-type">Usb</span> <span class="hljs-variable">keyBoard</span> <span class="hljs-operator">=</span> () -> System.out.println(<span class="hljs-string">"键盘开始工作了"</span>);
run(keyBoard);
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">run</span><span class="hljs-params">(Usb usb)</span>{
usb.service();
}
}
常用函数式接口
函数式接口 | 参数类型 | 返回类型 | 说明 |
---|---|---|---|
Consumer消费型接口 | T | void | void accept(T,t);对类型为T的对象应用操作 |
Supplier供给型接口 | 无 | T | T get();返回类型为T的对象 |
Function<T,R>函数型接口 | T | R | R apply(T,t);对类型为T的对象应用操作, 并返回类型为R的对象 |
Predicate断言型接口 | T | boolean | boolean test(T t);确定类型为T的对象是否满足条件, 并返回boolean类型 |
public class Demo02 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
// //匿名内部类
// Consumer<Double> consumer = new Consumer<Double>() {
// @Override
// public void accept(Double aDouble) {
// System.out.println("聚餐消费: " + aDouble);
// }
// };
//Lambda表达式
//Consumer<Double> consumer = aDouble -> System.out.println("聚餐消费: " + aDouble);
<span class="hljs-comment">//Consumer 消费型接口</span>
happy(aDouble -> System.out.println(<span class="hljs-string">"聚餐消费: "</span> + aDouble), <span class="hljs-number">1000</span>);<span class="hljs-comment">//聚餐消费: 1000.0</span>
happy(aDouble -> System.out.println(<span class="hljs-string">"唱歌消费: "</span> + aDouble), <span class="hljs-number">2000</span>);<span class="hljs-comment">//唱歌消费: 2000.0</span>
happy(aDouble -> System.out.println(<span class="hljs-string">"跳舞消费: "</span> + aDouble), <span class="hljs-number">3000</span>);<span class="hljs-comment">//跳舞消费: 3000.0</span>
<span class="hljs-comment">//Supplier 供给型接口</span>
<span class="hljs-type">int</span>[] arr = getNums(() -> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Random</span>().nextInt(<span class="hljs-number">100</span>), <span class="hljs-number">5</span>);
System.out.println(Arrays.toString(arr));<span class="hljs-comment">//[93, 9, 13, 1, 56] 5个随机数</span>
<span class="hljs-type">int</span>[] arr2 = getNums(() -> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Random</span>().nextInt(<span class="hljs-number">100</span>), <span class="hljs-number">10</span>);
System.out.println(Arrays.toString(arr2));<span class="hljs-comment">//[53, 94, 55, 59, 76, 74, 21, 61, 32, 94] 10个随机数</span>
<span class="hljs-comment">// Function 函数型接口</span>
<span class="hljs-type">String</span> <span class="hljs-variable">result1</span> <span class="hljs-operator">=</span> handleString(s -> s.toUpperCase(), <span class="hljs-string">"hello"</span>);<span class="hljs-comment">//转换为大写</span>
System.out.println(result1);<span class="hljs-comment">//HELLO</span>
<span class="hljs-type">String</span> <span class="hljs-variable">result2</span> <span class="hljs-operator">=</span> handleString(s -> s.trim(), <span class="hljs-string">" hello "</span>);<span class="hljs-comment">//去掉首尾空格</span>
System.out.println(result2);<span class="hljs-comment">//hello</span>
<span class="hljs-comment">// Predicate 断言型接口</span>
List<String> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
list.add(<span class="hljs-string">"张三"</span>);
list.add(<span class="hljs-string">"李四"</span>);
list.add(<span class="hljs-string">"李五"</span>);
list.add(<span class="hljs-string">"张四"</span>);
List<String> result3 = filterNames(s -> s.startsWith(<span class="hljs-string">"张"</span>), list);<span class="hljs-comment">//返回以"张"开头的字符串</span>
System.out.println(result3.toString());<span class="hljs-comment">//[张三, 张四]</span>
List<String> result4 = filterNames(s -> s.length() > <span class="hljs-number">1</span>, list);<span class="hljs-comment">//返回长度大于1的字符串</span>
System.out.println(result4);<span class="hljs-comment">//[张三, 李四, 李五, 张四]</span>
}
<span class="hljs-comment">//1. Consumer 消费型接口</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">happy</span><span class="hljs-params">(Consumer<Double> consumer, <span class="hljs-type">double</span> money)</span>{
consumer.accept(money);
}
<span class="hljs-comment">//2. Supplier 供给型接口</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-type">int</span>[] getNums(Supplier<Integer> supplier, <span class="hljs-type">int</span> count){
<span class="hljs-type">int</span>[] arr = <span class="hljs-keyword">new</span> <span class="hljs-title class_">int</span>[count];
<span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i < count; i++) {
arr[i] = supplier.get();
}
<span class="hljs-keyword">return</span> arr;
}
<span class="hljs-comment">//3. Function 函数型接口</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">handleString</span><span class="hljs-params">(Function<String, String> function, String str)</span>{
<span class="hljs-keyword">return</span> function.apply(str);
}
<span class="hljs-comment">//4. Predicate 断言型接口</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> List<String> <span class="hljs-title function_">filterNames</span><span class="hljs-params">(Predicate<String> predicate, List<String> list)</span>{
List<String> resultList = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><String>();
<span class="hljs-keyword">for</span> (String s : list) {
<span class="hljs-keyword">if</span> (predicate.test(s)){
resultList.add(s);
}
}
<span class="hljs-keyword">return</span> resultList;
}
}
折叠
四. 方法引用
- 方法调用时Lambda表达式的一种简写形式. 如果Lambda表达式方法体中只是调用一个人特定的已经存在的方法, 则可以使用方法引用
- 常见形式
- 对象::实例方法
- 类::静态方法
- 类::实例方法
- 类::new
public class Demo03 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//1. 对象::实例方法</span>
Consumer<String> consumer = s -> System.out.println(s);
consumer.accept(<span class="hljs-string">"hello"</span>);
Consumer<String> consumer2 = System.out::println;
consumer2.accept(<span class="hljs-string">"world"</span>);
<span class="hljs-comment">//2. 类::静态方法</span>
Comparator<Integer> com = (o1, o2) -> Integer.compare(o1, o2);
Comparator<Integer> com2 = Integer::compare;
<span class="hljs-comment">//3. 类::实例方法</span>
Function<Person, String> function = person -> person.getName();
Function<Person, String> function2 = Person::getName;
System.out.println(function2.apply(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"张三"</span>, <span class="hljs-number">13</span>)));
<span class="hljs-comment">//4. 类::new</span>
Supplier<Person> supplier = () -> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>();
Supplier<Person> supplier2 = Person::<span class="hljs-keyword">new</span>;
<span class="hljs-type">Person</span> <span class="hljs-variable">person</span> <span class="hljs-operator">=</span> supplier2.get();
System.out.println(person.toString());
}
}
五. Stream API
1. 什么是Stream
- 流(Stream)中保存对集合或数组数据的操作. 和集合类似, 但集合中保存的是数据
2. Stream特点
- Stream自己不会存储元素
- Stream不会改变源对象. 相反, 他们会返回一个持有结果的新Stream
- Stream操作是延迟执行的. 这意味着他们会等到需要结果的时候才执行
3. Stream使用步骤
- (1) 创建
- 新建一个流
- (2) 中间操作
- 在一个或多个步骤中, 将初始Stream转化到另一个Stream的中间操作
- (3) 终止操作
- 使用一个终止操作来产生一个结果. 该操作会强制它之前的延迟操作立即执行. 在这之后, 该Stream就不能使用了
(1) 创建Stream
- 通过Collection对象的stream()或parallelStream()方法
- 通过Arrays类的stream()方法
- 通过Stream接口的of(), iterate(), generate()方法
- 通过IntStream, LongStream, DoubleStream接口中的of, range, rangeClosed方法
public class Demo04 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//1. 通过Collection对象的stream()或parallelStream()方法</span>
ArrayList<String> arrayList = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
arrayList.add(<span class="hljs-string">"瓜子"</span>);
arrayList.add(<span class="hljs-string">"花生"</span>);
arrayList.add(<span class="hljs-string">"啤酒"</span>);
arrayList.add(<span class="hljs-string">"饮料"</span>);
Stream<String> stream = arrayList.parallelStream();<span class="hljs-comment">//parallelStream 并行流</span>
<span class="hljs-comment">//遍历</span>
stream.forEach(System.out::println);<span class="hljs-comment">//方法引用</span>
<span class="hljs-comment">//2. 通过Arrays类的stream()方法</span>
String[] arr = {<span class="hljs-string">"aaa"</span>, <span class="hljs-string">"bbb"</span>, <span class="hljs-string">"ccc"</span>};
Stream<String> stream2 = Arrays.stream(arr);
stream2.forEach(System.out::println);
<span class="hljs-comment">//3. 通过Stream接口的of(), iterate(), generate()方法</span>
<span class="hljs-comment">//3.1 of()</span>
System.out.println(<span class="hljs-string">"----------of()----------"</span>);
Stream<Integer> stream3 = Stream.of(<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>);
stream3.forEach(System.out::println);
<span class="hljs-comment">//3.2 迭代流iterate()</span>
System.out.println(<span class="hljs-string">"----------迭代流iterate()----------"</span>);
Stream<Integer> iterate = Stream.iterate(<span class="hljs-number">0</span>, x -> x + <span class="hljs-number">2</span>);
iterate.limit(<span class="hljs-number">10</span>).forEach(System.out::println);
<span class="hljs-comment">//3.3 生成流generate()</span>
System.out.println(<span class="hljs-string">"----------生成流generate()----------"</span>);
Stream<Integer> generate = Stream.generate(() -> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Random</span>().nextInt(<span class="hljs-number">100</span>));
generate.limit(<span class="hljs-number">10</span>).forEach(System.out::println);
<span class="hljs-comment">//4. 通过IntStream, LongStream, DoubleStream接口中的of, range, rangeClosed方法</span>
<span class="hljs-type">IntStream</span> <span class="hljs-variable">stream4</span> <span class="hljs-operator">=</span> IntStream.of(<span class="hljs-number">100</span>, <span class="hljs-number">200</span>,<span class="hljs-number">300</span>);
stream4.forEach(System.out::println);
<span class="hljs-type">IntStream</span> <span class="hljs-variable">range</span> <span class="hljs-operator">=</span> IntStream.range(<span class="hljs-number">0</span>, <span class="hljs-number">50</span>);
range.forEach(System.out::println);
}
}
折叠
(2) 中间操作
- 中间操作
- filter, limit, skip, distinct, sorted
- map
- parallel
public class Demo05 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
ArrayList<Person> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小一"</span>, <span class="hljs-number">18</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小三"</span>, <span class="hljs-number">20</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小二"</span>, <span class="hljs-number">19</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小四"</span>, <span class="hljs-number">21</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小二"</span>, <span class="hljs-number">19</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小四"</span>, <span class="hljs-number">21</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"小五"</span>, <span class="hljs-number">22</span>));
<span class="hljs-comment">//中间操作一: 1. filter过滤, 2. limit限制, 3. skip跳过, 4. distinct去重, 5. sorted排序</span>
<span class="hljs-comment">//1. filter过滤</span>
System.out.println(<span class="hljs-string">"------filter------"</span>);
list.stream()
.filter(e -> e.getAge() > <span class="hljs-number">20</span>)
.forEach(System.out::println);
<span class="hljs-comment">//2. limit限制</span>
System.out.println(<span class="hljs-string">"------limit------"</span>);
list.stream()
.limit(<span class="hljs-number">2</span>)
.forEach(System.out::println);
<span class="hljs-comment">//3. skip跳过</span>
System.out.println(<span class="hljs-string">"------skip------"</span>);
list.stream()
.skip(<span class="hljs-number">2</span>)
.forEach(System.out::println);
<span class="hljs-comment">//4. distinct去重(需重写hashcode和equals)</span>
System.out.println(<span class="hljs-string">"------distinct------"</span>);
list.stream()
.distinct()
.forEach(System.out::println);
<span class="hljs-comment">//5. sorted排序</span>
System.out.println(<span class="hljs-string">"------sorted------"</span>);
list.stream()
.sorted((p1, p2) -> Double.compare(p1.getAge(), p2.getAge()))
.forEach(System.out::println);
<span class="hljs-comment">//中间操作二: map</span>
System.out.println(<span class="hljs-string">"------map------"</span>);
list.stream()
.map(e -> e.getName())
.forEach(System.out::println);
<span class="hljs-comment">//中间操作三: parallel 并行: 采用多线程, 效率高</span>
System.out.println(<span class="hljs-string">"------parallel------"</span>);
list.parallelStream()
.forEach(System.out::println);
}
}
折叠
串行流和并行流的区别(并行流效率更高)
public class Demo06 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//串行流和并行流的区别</span>
ArrayList<String> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
<span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i < <span class="hljs-number">5000000</span>; i++) {
list.add(UUID.randomUUID().toString());
}
<span class="hljs-comment">//串行</span>
<span class="hljs-type">long</span> <span class="hljs-variable">start1</span> <span class="hljs-operator">=</span> System.currentTimeMillis();
<span class="hljs-type">long</span> <span class="hljs-variable">count1</span> <span class="hljs-operator">=</span> list.stream().sorted().count();
System.out.println(count1);<span class="hljs-comment">//5000000</span>
<span class="hljs-type">long</span> <span class="hljs-variable">end1</span> <span class="hljs-operator">=</span> System.currentTimeMillis();
System.out.println(<span class="hljs-string">"用时: "</span> + (end1 - start1));<span class="hljs-comment">//用时: 6750</span>
<span class="hljs-comment">//并行</span>
<span class="hljs-type">long</span> <span class="hljs-variable">start2</span> <span class="hljs-operator">=</span> System.currentTimeMillis();
<span class="hljs-type">long</span> <span class="hljs-variable">count2</span> <span class="hljs-operator">=</span> list.parallelStream().sorted().count();
System.out.println(count2);<span class="hljs-comment">//5000000</span>
<span class="hljs-type">long</span> <span class="hljs-variable">end2</span> <span class="hljs-operator">=</span> System.currentTimeMillis();
System.out.println(<span class="hljs-string">"用时: "</span> + (end2 - start2));<span class="hljs-comment">//用时: 3099</span>
}
}
(3) 终止操作
- 终止操作
- forEach, min, max, count
- reduce, collect
public class Demo07 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
ArrayList<Person> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"one"</span>, <span class="hljs-number">18</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"two"</span>, <span class="hljs-number">20</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"three"</span>, <span class="hljs-number">19</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"four"</span>, <span class="hljs-number">21</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"five"</span>, <span class="hljs-number">19</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"six"</span>, <span class="hljs-number">21</span>));
list.add(<span class="hljs-keyword">new</span> <span class="hljs-title class_">Person</span>(<span class="hljs-string">"seven"</span>, <span class="hljs-number">22</span>));
<span class="hljs-comment">//终止操作 forEach</span>
System.out.println(<span class="hljs-string">"------forEach------"</span>);
list.stream()
.filter(p -> {
System.out.println(<span class="hljs-string">"过滤了..."</span>);
<span class="hljs-keyword">return</span> p.getAge() > <span class="hljs-number">17</span>;
})
.forEach(System.out::println);
<span class="hljs-comment">//终止操作 min max count</span>
System.out.println(<span class="hljs-string">"------min------"</span>);
Optional<Person> min = list.stream()
.min((p1, p2) -> Double.compare(p1.getAge(), p2.getAge()));
System.out.println(min.get());
System.out.println(<span class="hljs-string">"------max------"</span>);
Optional<Person> max = list.stream()
.max((p1, p2) -> Double.compare(p1.getAge(), p2.getAge()));
System.out.println(max.get());
System.out.println(<span class="hljs-string">"------count------"</span>);
<span class="hljs-type">long</span> <span class="hljs-variable">count</span> <span class="hljs-operator">=</span> list.stream().count();
System.out.println(<span class="hljs-string">"学生个数: "</span> + count);
<span class="hljs-comment">//终止操作 reduce 规约</span>
<span class="hljs-comment">//计算所有学生的年龄和</span>
System.out.println(<span class="hljs-string">"------reduce------"</span>);
Optional<Integer> sum = list.stream()
.map(p -> p.getAge())
.reduce((x, y) -> x + y);
System.out.println(<span class="hljs-string">"年龄和为: "</span> + sum.get());
<span class="hljs-comment">//终止方法 collect 收集</span>
<span class="hljs-comment">//获取所有学生姓名, 封装成一个list集合</span>
List<String> names = list.stream()
.map(Person::getName)
.collect(Collectors.toList());
<span class="hljs-keyword">for</span> (String name : names) {
System.out.println(name);
}
}
}
折叠
六. 新时间 API
- 之前时间API存在问题: 线程安全问题, 设计混乱
- 所有新的日期时间 API 类都实现了一系列方法用以完成通用的任务,如:加、减、格式化、解析、从日期/时间中提取单独部分
- Java 8 中新的时间与日期 API 中的所有类都是不可变且线程安全的,任何修改操作都会返回一个新的实例
- 新的 API 区分各种日期时间概念并且各个概念使用相似的方法定义模式,这种相似性非常有利于 API 的学习。总结一下一般的方法或者方法前缀:
- of:静态工厂方法,用于创建实例
- now:静态工厂方法,用当前时间创建实例
- parse:静态工厂方法,从字符串解析得到对象实例
- get:获取时间日期对象的部分状态。
- is:检查某些东西的是否是 true,例如比较时间前后
- with:返回一个部分状态改变了的时间日期对象拷贝
- plus:返回一个时间增加了的、时间日期对象拷贝
- minus:返回一个时间减少了的、时间日期对象拷贝
- to:转换到另一个类型
- at:把这个对象与另一个对象组合起来,例如 date.atTime(time)
- format:提供格式化时间日期对象的能力
- 本地化日期时间 API
- LocalDate
- LocalTime
- LocalDateTime
- Instant: 时间戳
- ZoneId: 时区
- Date, Instant, LocalDateTime的转换
- DateTimeFormatter: 格式化类
(1) DateTimeFormatter
DateTimeFormatter这个类它只提供了时间格式化的类型,就是按你指定的格式,或者按jdk默认的格式,需要进行调用的则是时间类本身来进行调用才能进行格式化
public class Demo01 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//创建DateTimeFormatter</span>
<span class="hljs-type">DateTimeFormatter</span> <span class="hljs-variable">dtf</span> <span class="hljs-operator">=</span> DateTimeFormatter.ofPattern(<span class="hljs-string">"yyyy-MM-dd HH:mm:ss"</span>);
<span class="hljs-comment">//(1)把时间格式化成字符串</span>
<span class="hljs-type">String</span> <span class="hljs-variable">format</span> <span class="hljs-operator">=</span> dtf.format(LocalDateTime.now());
System.out.println(format);
<span class="hljs-comment">//(2)把字符串解析成时间</span>
<span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">localDateTime</span> <span class="hljs-operator">=</span> LocalDateTime.parse(<span class="hljs-string">"2021-03-13 23:01:35"</span>, dtf);
System.out.println(localDateTime);
}
}
public class Demo02 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> <span class="hljs-keyword">throws</span> Exception{
<span class="hljs-comment">//SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");//SimpleDateFormat类是线程不安全的</span>
<span class="hljs-type">DateTimeFormatter</span> <span class="hljs-variable">dtf</span> <span class="hljs-operator">=</span> DateTimeFormatter.ofPattern(<span class="hljs-string">"yyyyMMdd"</span>);<span class="hljs-comment">//格式化输出 线程安全</span>
<span class="hljs-type">ExecutorService</span> <span class="hljs-variable">pool</span> <span class="hljs-operator">=</span> Executors.newFixedThreadPool(<span class="hljs-number">10</span>);
Callable<LocalDate> callable = <span class="hljs-keyword">new</span> <span class="hljs-title class_">Callable</span><LocalDate>() {
<span class="hljs-meta">@Override</span>
<span class="hljs-keyword">public</span> LocalDate <span class="hljs-title function_">call</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception {
<span class="hljs-keyword">return</span> LocalDate.parse(<span class="hljs-string">"20210313"</span>, dtf);<span class="hljs-comment">//将特定格式的文本字符串解析为时间并返回</span>
}
};
List<Future<LocalDate>> list = <span class="hljs-keyword">new</span> <span class="hljs-title class_">ArrayList</span><>();
<span class="hljs-keyword">for</span> (<span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>; i < <span class="hljs-number">10</span>; i++) {
Future<LocalDate> future = pool.submit(callable);
list.add(future);
}
<span class="hljs-keyword">for</span> (Future<LocalDate> future : list) {
System.out.println(future.get());
}
pool.shutdown();
}
}
(2) LocalDateTime
public class Demo03 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//1. 创建本地时间</span>
<span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">localDateTime</span> <span class="hljs-operator">=</span> LocalDateTime.now();<span class="hljs-comment">//用当前时间创建实例</span>
<span class="hljs-comment">//LocalDateTime localDateTime1 = localDateTime.of();</span>
System.out.println(localDateTime);<span class="hljs-comment">//完整日期</span>
System.out.println(localDateTime.getYear());<span class="hljs-comment">//年</span>
System.out.println(localDateTime.getMonth());<span class="hljs-comment">//月</span>
System.out.println(localDateTime.getDayOfMonth());<span class="hljs-comment">//日</span>
System.out.println(localDateTime.getDayOfWeek());<span class="hljs-comment">//星期几</span>
System.out.println(localDateTime.getHour());<span class="hljs-comment">//时</span>
System.out.println(localDateTime.getMinute());<span class="hljs-comment">//分</span>
System.out.println(localDateTime.getSecond());<span class="hljs-comment">//秒</span>
<span class="hljs-comment">//2. 添加两天</span>
<span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">localDateTime1</span> <span class="hljs-operator">=</span> localDateTime.plusDays(<span class="hljs-number">2</span>);<span class="hljs-comment">//得到一个新的时间对象</span>
System.out.println(localDateTime1);
<span class="hljs-comment">//3. 减少一个月</span>
<span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">localDateTime2</span> <span class="hljs-operator">=</span> localDateTime.minusMonths(<span class="hljs-number">2</span>);
System.out.println(localDateTime2);
}
}
(3) Instant: 时间戳 + ZoneId: 时区
public class Demo04 {
<span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> {
<span class="hljs-comment">//1. 创建 Instant 时间戳</span>
<span class="hljs-type">Instant</span> <span class="hljs-variable">instant</span> <span class="hljs-operator">=</span> Instant.now();
System.out.println(instant.toString());<span class="hljs-comment">//2021-03-13T14:30:53.375Z 比北京时间少8小时</span>
System.out.println(instant.toEpochMilli());<span class="hljs-comment">//1615645853375</span>
System.out.println(System.currentTimeMillis());<span class="hljs-comment">//1615645853522</span>
<span class="hljs-comment">//2. 添加, 减少时间</span>
<span class="hljs-type">Instant</span> <span class="hljs-variable">instant1</span> <span class="hljs-operator">=</span> instant.plusMillis(TimeUnit.HOURS.toMillis(<span class="hljs-number">8</span>));<span class="hljs-comment">//通过增加8小时,转化为北京时间</span>
System.out.println(instant1);
System.out.println(Duration.between(instant, instant1).toMillis());<span class="hljs-comment">//28800000 instant和instant1之间相差28800000毫秒,也就是8小时</span>
<span class="hljs-comment">//3. ZoneId</span>
Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
<span class="hljs-keyword">for</span> (String availableZoneId : availableZoneIds) {
<span class="hljs-comment">//System.out.println(availableZoneId);</span>
}
System.out.println(ZoneId.systemDefault().toString());<span class="hljs-comment">//Asia/Shanghai</span>
<span class="hljs-comment">//4. Date ---> Instant ---> LocalDateTime</span>
System.out.println(<span class="hljs-string">"---------Date ---> Instant ---> LocalDateTime---------"</span>);
<span class="hljs-type">Date</span> <span class="hljs-variable">date</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Date</span>();
System.out.println(date);<span class="hljs-comment">//Sat Mar 13 22:30:53 CST 2021</span>
<span class="hljs-type">Instant</span> <span class="hljs-variable">instant2</span> <span class="hljs-operator">=</span> date.toInstant();<span class="hljs-comment">//Date转为Instant</span>
System.out.println(instant2);<span class="hljs-comment">//2021-03-13T14:30:53.558Z</span>
<span class="hljs-type">LocalDateTime</span> <span class="hljs-variable">localDateTime</span> <span class="hljs-operator">=</span> LocalDateTime.ofInstant(instant2, ZoneId.systemDefault());
System.out.println(localDateTime);<span class="hljs-comment">//2021-03-13T22:30:53.558</span>
<span class="hljs-comment">//5. LocalDateTime ---> Instant ---> Date</span>
System.out.println(<span class="hljs-string">"---------LocalDateTime ---> Instant ---> Date---------"</span>);
<span class="hljs-type">Instant</span> <span class="hljs-variable">instant3</span> <span class="hljs-operator">=</span> localDateTime.atZone(ZoneId.systemDefault()).toInstant();
System.out.println(instant3);
<span class="hljs-type">Date</span> <span class="hljs-variable">from</span> <span class="hljs-operator">=</span> Date.from(instant3);
System.out.println(from);
}
}
文章来源:https://www.cnblogs.com/qimu666/p/16565583.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!
标签: