利用 Fork/Join 框架,Arrays.parallelSort() 在多核 CPU 上大幅提升大數據量排序性能。測試 1 億整數排序,4 核平台上 parallelSort 耗時 7112ms,而 sort 耗時 16777ms。小數據量時 Fork/Join 開銷可能抵消收益。
Java 8 引入 java.util.stream.Stream,配合 Lambda 表達式,實現聲明式集合處理:
filter、map、flatMap 等,延遲執行,可鏈式調用forEach、count、reduce、collect 等,觸發實際計算// 篩選偶數並輸出第一個
IntStream.range(1,10).filter(i -> i % 2 == 0).findFirst().ifPresent(System.out::println);
// 所有元素乘2輸出
IntStream.range(1,10).map(i -> i * 2).forEach(System.out::println);
// 求和
int sum = IntStream.range(1, 10).reduce(0, Integer::sum);
// 字符串長度總和(兩種寫法等價)
int total = fruits.stream().reduce(0, (s, str) -> s + str.length(), Integer::sum);
int total2 = fruits.stream().mapToInt(String::length).reduce(0, Integer::sum);
// collect 避免中間對象創建
StringBuilder sb = fruits.stream().collect(StringBuilder::new,
(b, str) -> b.append(str.substring(0,1).toUpperCase()),
StringBuilder::append);
支持順序/並行切換:collection.stream() vs collection.parallelStream(),或 stream.sequential()/parallel()。
位於 java.time 包,基於 ISO 8601,解決舊 API 線程不安全、設計混亂問題。
LocalDateTime:無時區日期時間OffsetDateTime:帶 UTC 偏移量ZonedDateTime:帶時區規則Instant:時間戳(納秒精度)Duration:精確時間間隔(秒、小時、天)Period:日期間隔(年、月、日,考慮夏令時)Clock:可注入的時鐘,便於測試模擬不同時區/時間LocalDateTime.now().plusDays(3).minusHours(1).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
ZonedDateTime.now().withZoneSameInstant(ZoneId.of("GMT+08:00")).format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
DateTimeFormatter.ofPattern("yyyy MM dd").parse("2014 01 25").query(TemporalQueries.localDate());
標準庫終內置 java.util.Base64,無需第三方庫:
Base64.Encoder encoder = Base64.getEncoder();
String encoded = encoder.encodeToString("user:pass".getBytes());
Base64.Decoder decoder = Base64.getDecoder();
String decoded = new String(decoder.decode(encoded));
LongAdder、LongAccumulator、DoubleAdder、DoubleAccumulator:高並發下比 AtomicLong 吞吐更高ConcurrentHashMap 新增 compute、merge、search 等方法,構建緩存更簡單