JDK8的新特性(三)

本文已被阅读过 Posted by Liao Can on 2019-03-03

Optional类

常用方法

  1. Optional.of(T t):创建一个Optional实例
  2. Optional.empty():创建一个空的Optional实例
  3. Optional.ofNullable(T t):若t不为null,创建Optional实例,否则创建空实例
  4. isPresent():判断是否包含值
  5. orElse(T t):如果调用对象包含值,返回该值,否则返回t
  6. orElseGet(Supplier s):如果调用对象包含值,返回该值,否则返回 s 获取的值
  7. map(Function f):如果有值对其处理,并返回处理后Optional,否则返回Optional.empty()
  8. flatMap(Function mapper):与map类似,要求返回值必须是Optional

时间和日期

示例:jdk1.7解决线程安全问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DateFormatThreadLocal {

private static final ThreadLocal<DateFormat> df = new ThreadLocal<DateFormat>(){

protected DateFormat initialValue(){
return new SimpleDateFormat("yyyyMMdd");
}

};

public static final Date convert(String source) throws ParseException{
return df.get().parse(source);
}

public static void main(String[] args) throws Exception {
//解决多线程安全问题
Callable<Date> task = new Callable<Date>() {

@Override
public Date call() throws Exception {
return DateFormatThreadLocal.convert("20161121");
}

};

ExecutorService pool = Executors.newFixedThreadPool(10);

List<Future<Date>> results = new ArrayList<>();

for (int i = 0; i < 10; i++) {
results.add(pool.submit(task));
}

for (Future<Date> future : results) {
System.out.println(future.get());
}

pool.shutdown();
}
}

示例:jdk1.8解决线程安全问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class TestSimpleDateFormat {

public static void main(String[] args) throws Exception {
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMdd");

Callable<LocalDate> task = new Callable<LocalDate>() {

@Override
public LocalDate call() throws Exception {
LocalDate ld = LocalDate.parse("20161121", dtf);
return ld;
}

};

ExecutorService pool = Executors.newFixedThreadPool(10);

List<Future<LocalDate>> results = new ArrayList<>();

for (int i = 0; i < 10; i++) {
results.add(pool.submit(task));
}

for (Future<LocalDate> future : results) {
System.out.println(future.get());
}

pool.shutdown();
}

}

示例:时间API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);

LocalDateTime ld2 = LocalDateTime.of(2016, 11, 21, 10, 10, 10);
System.out.println(ld2);

LocalDateTime ldt3 = ld2.plusYears(20);
System.out.println(ldt3);

LocalDateTime ldt4 = ld2.minusMonths(2);
System.out.println(ldt4);

System.out.println(ldt.getYear());
System.out.println(ldt.getMonthValue());
System.out.println(ldt.getDayOfMonth());
System.out.println(ldt.getHour());
System.out.println(ldt.getMinute());
System.out.println(ldt.getSecond());

示例:时间戳API

1
2
3
4
5
6
7
8
9
10
Instant ins = Instant.now();  //默认使用 UTC 时区
System.out.println(ins);

OffsetDateTime odt = ins.atOffset(ZoneOffset.ofHours(8));
System.out.println(odt);

System.out.println(ins.getNano());

Instant ins2 = Instant.ofEpochSecond(5);
System.out.println(ins2);

示例:计算时间和日期间隔

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Instant ins1 = Instant.now();

System.out.println("--------------------");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}

Instant ins2 = Instant.now();

System.out.println("所耗费时间为:" + Duration.between(ins1, ins2));

System.out.println("----------------------------------");

LocalDate ld1 = LocalDate.now();
ld2 = LocalDate.of(2011, 1, 1);

Period pe = Period.between(ld2, ld1);
System.out.println(pe.getYears());
System.out.println(pe.getMonths());
System.out.println(pe.getDays());

示例:时间校正器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
LocalDateTime ldt = LocalDateTime.now();
System.out.println(ldt);

LocalDateTime ldt2 = ldt.withDayOfMonth(10);
System.out.println(ldt2);

LocalDateTime ldt3 = ldt.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(ldt3);

//自定义:下一个工作日
LocalDateTime ldt5 = ldt.with((l) -> {
LocalDateTime ldt4 = (LocalDateTime) l;

DayOfWeek dow = ldt4.getDayOfWeek();

if(dow.equals(DayOfWeek.FRIDAY)){
return ldt4.plusDays(3);
}else if(dow.equals(DayOfWeek.SATURDAY)){
return ldt4.plusDays(2);
}else{
return ldt4.plusDays(1);
}
});

System.out.println(ldt5);

示例:时间/日期格式化

1
2
3
4
5
6
7
8
9
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss E");

LocalDateTime ldt = LocalDateTime.now();
String strDate = ldt.format(dtf);

System.out.println(strDate);

LocalDateTime newLdt = LocalDateTime.parse(strDate, dtf);
System.out.println(newLdt);

示例:带时区的时间

1
2
3
4
5
6
7
8
Set<String> set = ZoneId.getAvailableZoneIds(); // 获取所有时区
set.forEach(System.out::println);

LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
System.out.println(ldt);

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("US/Pacific"));
System.out.println(zdt);

注解

类型注解

教程
https://my.oschina.net/benhaile/blog/179642

重复注解

教程
http://www.importnew.com/14919.html

Base64

示例:使用Base64编码与解码

1
2
3
4
5
6
7
8
9
10
11
final String text = "Base64 finally in Java 8!";

final String encoded = Base64
.getEncoder()
.encodeToString( text.getBytes( StandardCharsets.UTF_8 ) );
System.out.println( encoded );

final String decoded = new String(
Base64.getDecoder().decode( encoded ),
StandardCharsets.UTF_8 );
System.out.println( decoded );

并行数组

示例:数组并行排序

1
2
3
4
5
6
7
8
9
10
11
12
long[] arrayOfLong = new long [ 20000 ];        

Arrays.parallelSetAll( arrayOfLong,
index -> ThreadLocalRandom.current().nextInt( 1000000 ) );
Arrays.stream( arrayOfLong ).limit( 10 ).forEach(
i -> System.out.print( i + " " ) );
System.out.println();

Arrays.parallelSort( arrayOfLong );
Arrays.stream( arrayOfLong ).limit( 10 ).forEach(
i -> System.out.print( i + " " ) );
System.out.println();

JVM

JVM选项-XX:PermSize与-XX:MaxPermSize分别被-XX:MetaSpaceSize与-XX:MaxMetaspaceSize所代替。

示例:JVM典型配置
JAVA_OPTS="-server -Xms1g -Xmx4g -XX:MetaspaceSize=64m -XX:MaxMetaspaceSize=1024m -Duser.timezone=GMT+8"
参数说明
参数 说明
-server 服务器模式
-Xms 初始分配的堆内存
-Xmx 最大允许分配的堆内存,按需分配
-XX:MetaspaceSize 元空间初始分配的内存
-XX:MaxMetaspaceSize 元空间最大允许分配的内存
-Duser.timezone 设置时区


支付宝打赏 微信打赏

赞赏一下