注:在2017年3月編寫的版本的基礎(chǔ)上,按簡(jiǎn)書要求清除了外鏈窜管,一些外部信息請(qǐng)自行檢索
Java8引入了哪些新特性橄仍?
- Lambda表達(dá)式
- Optional
- Stream
- 默認(rèn)方法
- CompletableFuture
- 新的日期和時(shí)間api
為何要關(guān)心這些特性
- 聲明式編程 vs 命令式編程
- 響應(yīng)式編程 vs 多線程編程
- 面向函數(shù) vs 面向?qū)ο?/li>
Java 8 提供了更多的編程工具和概念韧涨,能夠以更簡(jiǎn)潔、更易于維護(hù)的方式解決新的和現(xiàn)有的編程問(wèn)題侮繁。
在Java6,7的環(huán)境中使用Java8的新特性
retrolambda:支持Lambda表達(dá)式,方法引用,接口靜態(tài)方法的backport庫(kù)
streamsupport:支持Stream,CompletableFuture,函數(shù)接口,Optional的backport庫(kù)
threetenbp:支持Java8時(shí)間日期api的backport庫(kù)
lambda表達(dá)式
Lambda表達(dá)式是一個(gè)匿名函數(shù)虑粥,可以作為參數(shù)傳遞給方法或者存儲(chǔ)在變量中。
Lambda表達(dá)式有參數(shù)列表宪哩、函數(shù)主體娩贷、返回類型,可以拋出異常锁孟。
Java中的lambda表達(dá)式僅僅是替代匿名內(nèi)部類的語(yǔ)法糖彬祖。
聲明表達(dá)式的例子↓
Runnable run = () -> {};
Runnable run = new Runnable() {
@Override
public void run() {
}
};
BiFunction<Long, Long, Long> adder = (Long x, Long y) -> { return x + y; };
BiFunction<Long, Long, Long> adder = (x, y) -> x + y;
BiFunction<Long, Long, Long> adder = new BiFunction<Long, Long, Long>() {
@Override
public Long apply(Long x, Long y) {
return x + y;
}
};
Consumer<String> sayHi = (String name) -> System.out.println("Hi " + name);
Consumer<String> sayHi = new Consumer<String>() {
@Override
public void accept(String name) {
System.out.println("Hi " + name);
}
};
FileFilter filter = f -> f.isDirectory();
FileFilter filter = new FileFilter() {
@Override
public boolean accept(File f) {
return f.isDirectory();
}
};
局限性: 必須顯式或隱式的通過(guò)函數(shù)式接口聲明Lambda表達(dá)式 (表達(dá)式相同茁瘦,函數(shù)接口不同,則用途不同)储笑。
函數(shù)式接口: 只定義一個(gè)抽象方法的接口 (可通過(guò)標(biāo)注@FunctionalInterface提示編譯器進(jìn)行檢查)甜熔。
目標(biāo)類型: Lambda表達(dá)式需要的類型。Lambda表達(dá)式的類型會(huì)從上下文中推斷出來(lái)(類似List<String> list = new ArrayList<>;
)突倍。
隱式聲明表達(dá)式的例子↓
file.listFiles(f -> f.isFile() && !f.isHidden());
file.listFiles(new FileFilter() {
@Override
public boolean accept(File f) {
return f.isFile() && !f.isHidden();
}
});
file.listFiles((dir, name) -> name.endsWith(".class"));
file.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(".class");
}
});
List<Integer> list = Arrays.asList(3, 5, 2, 1, 6);
list.sort((a, b) -> a.compareTo(b));
list.sort(new Comparator<Integer>() {
@Override
public int compare(Integer a, Integer b) {
return a.compareTo(b);
}
});
常用的函數(shù)式接口 (java.util.function.*)↓
函數(shù)式接口 | 函數(shù)描述符 | 使用場(chǎng)景 |
---|---|---|
Predicate<T> | T → boolean | 各種filter |
Consumer<T> | T → void | forEach的情形 |
Supplier<T> | () → T | 工廠函數(shù) |
Function<T, R> | T → R | 對(duì)象轉(zhuǎn)換 |
BiFunction<T, U, R> | (T, U) → R | 對(duì)象轉(zhuǎn)換 |
UnaryOperator<T> | T → T | 一元運(yùn)算符 |
BinaryOperator<T> | (T, T) → T | 二元運(yùn)算符 |
方法引用
靜態(tài)方法引用 ↓
Function<String, Integer> parser = Integer::parseInt;
Function<String, Integer> parser = str -> Integer.parseInt(str);
實(shí)例方法引用↓
List<Integer> list = Arrays.asList(3, 5, 2, 1, 6);
list.sort(Integer::compareTo);
list.sort((a, b) -> a.compareTo(b));
// 下面的語(yǔ)句對(duì)應(yīng)靜態(tài)方法引用
list.sort(Integer::compare);
對(duì)象方法引用↓
CountDownLatch latch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
new Thread(latch::countDown).start();
// 等價(jià)于
// new Thread(() -> { latch.countDown(); }).start();
}
latch.await();
構(gòu)造方法引用↓
Executors.newCachedThreadPool(Thread::new);
Executors.newCachedThreadPool(r -> new Thread(r));
Executors.newCachedThreadPool(new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r);
}
});
一些有用的Lambda復(fù)合方法 (將多個(gè)表達(dá)式整合成一個(gè))
java.util.Comparator提供的復(fù)合方法↓
List<Repo> repos = Arrays.asList(
new Repo("code-service", true),
new Repo("code-office", false),
new Repo("code-browser", true));
repos.sort(Comparator
.comparing(Repo::isFavorite)
.reversed()
.thenComparing(Repo::getName));
repos.stream().forEach(System.out::println);
輸出結(jié)果↓
code-browser true code-service true code-office false
java.util.function.Predicate提供的復(fù)合方法↓
IntPredicate p23 = v -> v % 23 == 0;
IntPredicate p3 = v -> v % 3 == 0;
IntPredicate p37 = v -> v % 37 == 0;
IntStream.rangeClosed(1, 100)
.filter(p23
.and(p3.negate())
.or(p37))
.forEach(v -> System.out.print(v + " "));
輸出結(jié)果:23 37 46 74 92
java.util.function.Function提供的復(fù)合方法↓
Function<Integer, Integer> f = x -> x + 1;
Function<Integer, Integer> g = x -> x * 2;
Function<Integer, Integer> h = f.andThen(g); // 等價(jià)于 x -> (x + 1) * 2
** 注意事項(xiàng)**
- Lambda表達(dá)式中的this
靜態(tài)方法中聲明的Lambda表達(dá)式腔稀,內(nèi)部不允許出現(xiàn)this
類實(shí)例的方法中聲明的Lambda表達(dá)式,內(nèi)部出現(xiàn)的this直接指向類實(shí)例本身 - 在表達(dá)式內(nèi)部對(duì)外部變量進(jìn)行引用(打折扣的閉包)
Lambda表達(dá)式內(nèi)部引用的方法中的局部變量羽历,必須是不可變的(即使未聲明final關(guān)鍵字) - Lambda表達(dá)式會(huì)讓棧跟蹤的分析變得更困難
Optional
“I call it my billion-dollar mistake. ... My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement.”
from 《Invention of the null-reference a billion dollar mistake》
by Tony Hoare
null的壞處: 缺乏安全感
String name = revision.getCommit().getCommitter().getName();
通過(guò)使用Optional烧颖,消除業(yè)務(wù)代碼中對(duì)null的判斷
class RevisionInfo {
private CommitInfo commit;
public RevisionInfo(CommitInfo commit) {
this.commit = commit;
}
public CommitInfo getCommit() {
return commit;
}
}
class CommitInfo {
private String commit;
private GitPersonInfo committer;
public CommitInfo(String commit, GitPersonInfo committer){
this.commit = commit;
this.committer = committer;
}
public String getCommit() {
return commit;
}
public GitPersonInfo getCommitter() {
return committer;
}
}
class GitPersonInfo {
private String name;
public GitPersonInfo(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
// 構(gòu)造數(shù)據(jù)
GitPersonInfo personInfo = new GitPersonInfo("yangziwen");
CommitInfo commitInfo = new CommitInfo("e0f181e", personInfo);
RevisionInfo revision = new RevisionInfo(commitInfo);
// 不使用Optional的寫法
String name = "";
if (revision != null) {
CommitInfo commit = revision.getCommit();
if (commit != null) {
GitPersonInfo person = commit.getCommitter();
if (person != null) {
name = person.getName();
}
}
}
// 使用Optional的寫法
String name = Optional.ofNullable(revision)
.map(RevisionInfo::getCommit)
.map(CommitInfo::getCommitter)
.map(GitPersonInfo::getName)
.orElse("");
// 等價(jià)的寫法
String name = Optional.ofNullable(revision)
.map(rev -> rev.getCommit())
.map(commit -> commit.getCommitter())
.map(commiter -> commiter.getName())
.orElse("");
藉此實(shí)現(xiàn)了類似groovy中 def name = revision?.commit?.committer?.name?:""
的效果
可通過(guò)如下方式創(chuàng)建Optional對(duì)象
Optional<String> optional = Optional.of("hello");
Optional<String> optional = Optional.ofNullable("world");
Optional<String> optional = Optional.empty();
注意事項(xiàng)
- Optional類沒(méi)有實(shí)現(xiàn)Serializable接口
- 不要在Model或DTO類中直接使用Optional做為字段類型
- 盡量不使用Optional的基礎(chǔ)類型 (如OptionalInt, OptionalLong)
Stream
遍歷數(shù)據(jù)集的高級(jí)迭代器
允許以聲明性方式處理數(shù)據(jù)集合,類似linux中的管道窄陡,或者jQuery的集合操作
List<Integer> list = Arrays.asList(3, 5, 1, 7, 2, 9, 3, 9, 1);
// 去重后炕淮,取出最大的三個(gè)奇數(shù)
List<Integer> threeBiggestOdds = list.stream()
.distinct()
.filter(d -> d % 2 == 1)
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
// 不使用流的方式
Set<Integer> set = new TreeSet<>(new Comparator<Integer>() {
@Override
public int compare(Integer v1, Integer v2) {
return v2.compareTo(v1);
}
});
for (Integer v : list) {
if (v % 2 == 1) {
set.add(v);
}
}
List<Integer> threeBiggestOdds = new ArrayList<>(set).subList(0, 3);
結(jié)果[9, 7, 5]
流的操作
中間操作:filter, map, sorted, skip, limit等 (繼續(xù)返回Stream對(duì)象)
終端操作:collect, forEach, min, max, count, anyMatch, findFirst等
一個(gè)Stream對(duì)象只能消費(fèi)(遍歷)一次,遍歷的執(zhí)行由終端操作觸發(fā)
int[] numbers = {4, 5, 3, 9};
// 求和
int result = Arrays.stream(numbers).reduce(0, (a, b) -> a + b);
// 等價(jià)于
int result = Arrays.stream(numbers).sum();
數(shù)值流
IntStream intStream = dishList.stream().mapToInt(Dish::getCalories);
Stream<Integer> stream = intStream.boxed();
IntStream.rangeClosed(1, 100).sum();
并行流
// 任務(wù)被分治拆解后跳夭,通過(guò)ForkJoinPool并行執(zhí)行
List<Integer> threeBiggestOdds = list.parallelStream() // 直接創(chuàng)建并行流
.distinct()
.filter(d -> d % 2 == 1)
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
List<Integer> threeBiggestOdds = list.stream()
.distinct()
.filter(d -> d % 2 == 1)
.parallel() // 在某一步轉(zhuǎn)換為并行流
.sorted(Comparator.reverseOrder())
.limit(3)
.collect(Collectors.toList());
用流重構(gòu)代碼
簡(jiǎn)單的例子
重構(gòu)前↓
public List<GroupMember> getUsersByProduct(Product product, RepoMemberRole role) {
List<ProductGroupRelation> relations = getProductGroupRelationsByProductId(product.getId());
List<Long> groupIds = new ArrayList<>();
for (ProductGroupRelation relation : relations) {
if (role == null || role == relation.getRole()) {
groupIds.add(relation.getGroupId());
}
}
return groupService.getMembersByGroupIds(groupIds);
}
重構(gòu)后↓
public List<GroupMember> getusersByProduct(Product product, RepoMemberRole role) {
return getProductGroupRelationsByProductId(product.getId())
.stream()
.filter(rel -> role == null || role == rel.getRole())
.map(rel -> rel.getGroupId())
.collect(collectingAndThen(toList(), groupService::getMembersByGroupIds));
}
復(fù)雜一些的例子
重構(gòu)前↓
public List<RepoMember> getRepoUsers(Repo repo) {
List<RepoMember> users = repoMemberDao.selectRepoMemberByRepoID(repo.getId());
users.addAll(getRepoUsersViaGroup(repo));
Map<String, RepoMember> userMap = new HashMap<>();
for (RepoMember user : users) {
RepoMember prev = userMap.get(user.getUserName());
if (prev == null) {
userMap.put(user.getUserName(), user);
continue;
}
if (prev.getRepoMemberRole().hasPermission(user.getRepoMemberRole())) {
continue;
}
userMap.put(user.getUserName(), user);
}
List<RepoMember> result = Lists.newArrayList(userMap.values());
Collections.sort(result, new Comparator<RepoMember>() {
@Override
public int compare(RepoMember user1, RepoMember user2) {
int result = user1.getRepoMemberRole().compareTo(user2.getRepoMemberRole());
if (result == 0) {
result = user1.getUserName().compareTo(user2.getUserName());
}
return result;
}
});
return result;
}
使用流重構(gòu)后↓
public List<RepoMember> getRepoUsers(Repo repo) {
return Stream.concat(
repoMemberDao.selectRepoMemberByRepoID(repo.getId()).stream(),
getRepoUsersViaGroup(repo).stream())
.collect(groupingBy(RepoMember::getUserName)) // 構(gòu)造userListMap
.values().stream()
.map(list -> list.stream().min(comparing(RepoMember::getRepoMemberRole))) // 每個(gè)user的最大權(quán)限
.filter(Optional::isPresent)
.map(Optional::get)
.sorted(comparing(RepoMember::getRepoMemberRole)
.thenComparing(RepoMember::getUserName)) // 先按角色排序涂圆,再按用戶名排序
.collect(toList());
}
注意事項(xiàng)
- 并行流只適用于計(jì)算密集型的場(chǎng)景,不適合簡(jiǎn)單計(jì)算和IO密集型的場(chǎng)景
- 要注意使用流過(guò)程中基本類型的拆箱裝箱操作對(duì)性能的影響
默認(rèn)方法
接口中可定義以default關(guān)鍵字開(kāi)頭的非抽象非靜態(tài)的方法
用來(lái)對(duì)接口進(jìn)行擴(kuò)展币叹,可被實(shí)現(xiàn)類覆蓋(Override)
默認(rèn)方法只能調(diào)用本接口中的其他抽象方法或默認(rèn)方法
// List接口中的sort方法
@SuppressWarnings({"unchecked", "rawtypes"})
default void sort(Comparator<? super E> c) {
Object[] a = this.toArray();
Arrays.sort(a, (Comparator) c);
ListIterator<E> i = this.listIterator();
for (Object e : a) {
i.next();
i.set((E) e);
}
}
多繼承問(wèn)題
接口中允許聲明默認(rèn)方法,造成了方法多繼承問(wèn)題的出現(xiàn)
解決問(wèn)題的三條規(guī)則
類中聲明的方法的優(yōu)先級(jí)高于接口中聲明的默認(rèn)方法
-
子接口中的默認(rèn)方法的優(yōu)先級(jí)高于父接口
-
繼承了多個(gè)接口的類必須通過(guò)顯示覆蓋和調(diào)用期望的方法,顯式的選擇使用哪個(gè)默認(rèn)方法的實(shí)現(xiàn)
interface A {
default void hello () {
System.out.println("Hello A");
}
}
interface B {
default void hello() {
System.out.println("Hello B");
}
}
class C implements A, B {
@Override
public void hello() {
A.super.hello();
}
}
CompletableFuture
Future接口只能以阻塞的方式獲取結(jié)果,因此引入CompletableFuture,從而可以非阻塞(回調(diào))的方式獲取和處理結(jié)果
類似jQuery中基于Promise/Deferred模式的ajax api
輔助代碼↓
static long now() {
return System.currentTimeMillis();
}
// 產(chǎn)生一個(gè)1s到3s的延遲,模仿IO操作
static double randomDelay() {
long t = now();
sleepQuietly((new Random().nextInt(20) + 10) * 100L);
return (now() - t) / 1000D;
}
static void sleepQuietly(Long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
}
}
例子1:串行的執(zhí)行兩個(gè)IO操作祸憋,并通過(guò)回調(diào)的方式處理結(jié)果
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(10);
long t = now();
CompletableFuture.supplyAsync(() -> {
System.out.println("delay before task is " + (now() - t) / 1000D);
return randomDelay();
}, executor)
.thenAccept(d1 -> System.out.println("delay of 1st task is " + d1))
.thenCompose(d1 -> CompletableFuture.supplyAsync(() -> {
return randomDelay();
}, executor))
.thenAccept(d2 -> System.out.println("delay of 2nd task is " + d2))
.thenAccept(d2 -> System.out.println("total time is " + (now() - t) / 1000D))
.thenAcceptAsync(d2 -> executor.shutdown());
}
例子2:并行的執(zhí)行兩個(gè)IO操作巍沙,并通過(guò)回調(diào)的方式處理結(jié)果
static final ExecutorService executor = Executors.newFixedThreadPool(10);
public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
return CompletableFuture.supplyAsync(supplier, executor);
}
public static void main(String[] args) {
long t = now();
supplyAsync(() -> {
System.out.println("delay before task is " + (now() - t) / 1000D);
return randomDelay();
}).thenCombine(supplyAsync(() -> {
return randomDelay();
}), (d1, d2) -> Arrays.asList(d1, d2))
.thenAccept(delays -> {
AtomicInteger counter = new AtomicInteger(0);
delays.stream().forEach(delay -> {
System.out.println("delay of task" + counter.incrementAndGet() + " is " + delay);
});
System.out.println("total delay is " + (now() - t) / 1000D);
})
.thenAcceptAsync(delays -> executor.shutdown());
}
注意事項(xiàng)
- 基于Blocking-IO的IO密集型應(yīng)用不要使用ForkJoinPool (CompletableFuture默認(rèn)使用ForkJoinPool牍疏,因此需指定自定義的線程池)
- 在高并發(fā)下厦滤,線程數(shù)的設(shè)置可參考如下公式
Nthreads:高并發(fā)下線程池的理想線程數(shù)
NCPU:CPU內(nèi)核個(gè)數(shù)忍啸,可通過(guò)Runtime.getRuntime().availableProcessors()
獲取
UCPU:CPU總利用率悄晃,取值在0到1之間
W / C:CPU占空比(C為占用的時(shí)間,W為空閑的時(shí)間)
新的日期和時(shí)間api
Java曾經(jīng)在同一個(gè)地方摔倒了兩次 → Date and Calendar
new Date(117, 1, 16); // 2017-02-16
DateFormat // 線程不安全
Calendar // 仍然不好用 (線程不安全,可變妈橄,不支持格式化)
為了阻止悲劇反復(fù)上演庶近,Java8決定整合Joda-Time的特性
LocalDate / LocalTime / LocalDateTime
LocalDate date = LocalDate.of(2017, 2, 16);
LocalDate today = LocalDate.now();
LocalDate date = LocalDate.parse("2017-02-16"); // 只拋運(yùn)行時(shí)異常
DateTimeFormatter formatter = new DateTimeFormatter.ofPattern("yyyy/MM/dd"); // 線程安全
LocalDate date = LocalDate.parse("2017/02/16", formatter); // 只拋運(yùn)行時(shí)異常
Period // 按日計(jì)的時(shí)間間隔
Duration // 按秒記得時(shí)間間隔
TemporalAdjuster 調(diào)整日期時(shí)間
import static java.time.temporal.TemporalAdjusters.*;
LocalDate date = LocalDate.parse("2017-02-16").with(nextOrSame(DayOfWeek.SATURDAY));
時(shí)區(qū)
ZonedDateTime time = LocalDateTime.now().atZone(ZoneId.systemDefault());
ZonedDateTime londonTime = time.withZoneSameInstant(ZoneId.of("Europe/London"));
歷法
ThaiBuddhistDate // 泰國(guó)佛教歷
MinguoDate // 中華民國(guó)歷
JapaneseDate // 日本歷
HijrahDate // 伊斯蘭歷
MinguoDate date = MinguoDate.from(LocalDate.parse("2017-02-16"));
// Minguo ROC 106-02-16
JapaneseDate date = JapaneseDate.from(LocalDate.parse("2017-02-16"));
// Japanese Heisei 29-02-16
注意事項(xiàng)
- 所有的日期和時(shí)間對(duì)象,都是不可變對(duì)象眷蚓,所以一定是線程安全的
- 盡量不用各種其他的歷法(ChronoLocalDate)鼻种,在系統(tǒng)中統(tǒng)一使用LocalDate(ISO-8061的時(shí)間和日期標(biāo)準(zhǔn))
- LocalDateTime應(yīng)用于MyBatis,需要自定義相應(yīng)類型的handler沙热,實(shí)現(xiàn)java.sql.Timestamp與LocalDateTime之間的轉(zhuǎn)換
更多內(nèi)容:JAVA 8:健壯叉钥、易用的時(shí)間/日期API