基于 Java 17 LTS,涵盖 java.lang、java.util、java.time、java.io 等核心包

1. String 类

java.lang.String — 不可变字符序列,UTF-16 编码。

1.1 构造方法

构造方法 说明
String() 创建空字符串 ""
String(String original) 拷贝构造
String(char[] value) 从字符数组创建
String(char[] value, int offset, int count) 从字符数组的子区间创建
String(byte[] bytes) 从字节数组创建(平台默认编码)
String(byte[] bytes, Charset charset) 从字节数组创建(指定编码)
String(byte[] bytes, int offset, int length) 从字节数组子区间创建
String(byte[] bytes, int offset, int length, Charset charset) 从字节数组子区间创建(指定编码)

1.2 长度与判空

方法 返回值 说明
length() int 返回字符串长度(字符数)
isEmpty() boolean length() == 0 时返回 true
isBlank() boolean 当字符串为空或仅含空白字符时返回 true(Java 11+)
String s = "  ";
s.length();      // 2
s.isEmpty();     // false
s.isBlank();     // true

1.3 字符/字节访问

方法 返回值 说明
charAt(int index) char 返回指定索引处的字符
codePointAt(int index) int 返回指定索引处的 Unicode 码点
codePointBefore(int index) int 返回指定索引前一个字符的 Unicode 码点
codePointCount(int beginIndex, int endIndex) int 返回指定范围内的 Unicode 码点数量
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) void 将字符复制到目标数组
getBytes() byte[] 使用平台默认编码转为字节数组
getBytes(Charset charset) byte[] 使用指定编码转为字节数组
getBytes(String charsetName) byte[] 使用指定编码名转为字节数组
toCharArray() char[] 转为字符数组

1.4 比较

方法 返回值 说明
equals(Object anObject) boolean 比较字符串内容是否相等
equalsIgnoreCase(String anotherString) boolean 忽略大小写比较
compareTo(String anotherString) int 字典序比较。返回 0 / 负数 / 正数
compareToIgnoreCase(String str) int 忽略大小写的字典序比较
contentEquals(CharSequence cs) boolean 与 CharSequence 内容比较
contentEquals(StringBuffer sb) boolean 与 StringBuffer 内容比较
"abc".compareTo("abd");   // -1
"abc".compareTo("abc");   // 0
"abc".compareTo("abb");   // 1

1.5 查找

方法 返回值 说明
indexOf(int ch) int 查找字符首次出现的位置,未找到返回 -1
indexOf(int ch, int fromIndex) int 从指定位置开始查找字符
indexOf(String str) int 查找子串首次出现的位置
indexOf(String str, int fromIndex) int 从指定位置开始查找子串
lastIndexOf(int ch) int 查找字符最后出现的位置
lastIndexOf(int ch, int fromIndex) int 从指定位置反向查找字符
lastIndexOf(String str) int 查找子串最后出现的位置
lastIndexOf(String str, int fromIndex) int 从指定位置反向查找子串
contains(CharSequence s) boolean 是否包含指定字符序列
startsWith(String prefix) boolean 是否以指定前缀开头
startsWith(String prefix, int toffset) boolean 从指定偏移处是否以指定前缀开头
endsWith(String suffix) boolean 是否以指定后缀结尾
"hello world".indexOf('o');       // 4
"hello world".indexOf('o', 5);    // 7
"hello world".lastIndexOf('o');   // 7
"hello world".contains("wo");     // true
"hello world".startsWith("he");   // true
"hello world".endsWith("ld");     // true

1.6 提取子串

方法 返回值 说明
substring(int beginIndex) String 从指定位置提取到末尾
substring(int beginIndex, int endIndex) String 提取 [beginIndex, endIndex) 子串
subSequence(int beginIndex, int endIndex) CharSequence 返回字符序列(同 substring)
"hello".substring(1);      // "ello"
"hello".substring(1, 4);   // "el"

1.7 替换

方法 返回值 说明
replace(char oldChar, char newChar) String 替换所有字符
replace(CharSequence target, CharSequence replacement) String 替换所有字面匹配的子串
replaceAll(String regex, String replacement) String 使用正则替换
replaceFirst(String regex, String replacement) String 使用正则替换第一个匹配
"a,b,c".replace(',', '-');          // "a-b-c"
"a,b,c".replaceAll("[a-c]", "x");   // "x,x,x"
"a,b,c".replaceFirst(",", ";");     // "a;b,c"

1.8 大小写转换

方法 返回值 说明
toLowerCase() String 转为小写(默认区域)
toLowerCase(Locale locale) String 转为小写(指定区域)
toUpperCase() String 转为大写(默认区域)
toUpperCase(Locale locale) String 转为大写(指定区域)

1.9 去除空白

方法 返回值 说明
trim() String 去除首尾空白(仅限 ≤ ' ' 的字符)
strip() String 去除首尾空白(Unicode 全量,Java 11+)
stripLeading() String 去除前导空白(Java 11+)
stripTrailing() String 去除尾部空白(Java 11+)
stripIndent() String 去除行首公共缩进(Java 15+)
trim() vs strip() trim() 只移除 ASCII 空格;strip() 移除所有 Unicode 空白

1.10 分割与连接

方法 返回值 说明
split(String regex) String[] 按正则分割
split(String regex, int limit) String[] 按正则分割,限制分段数
join(CharSequence delimiter, CharSequence... elements) String 用分隔符连接(静态方法)
join(CharSequence delimiter, Iterable<? extends CharSequence> elements) String 用分隔符连接 Iterable(静态方法)
"a,b,c".split(",");                  // ["a", "b", "c"]
"a,b,c".split(",", 2);               // ["a", "b,c"]
String.join("-", "2024", "01", "01"); // "2024-01-01"

1.11 格式化

方法 返回值 说明
format(String format, Object... args) static String 格式化字符串(使用 Formatter
format(Locale l, String format, Object... args) static String 指定区域的格式化
formatted(Object... args) String 实例方法,等价于 String.format(this, args)(Java 15+)
String.format("Hello, %s! You have %d messages.", "Alice", 3);
// "Hello, Alice! You have 3 messages."

"Age: %d".formatted(25);  // "Age: 25"

常用格式说明符:

格式符 说明 示例
%s 字符串 "hi"
%d 十进制整数 42
%f 浮点数 3.140000
%.2f 浮点数(2 位小数) 3.14
%n 平台换行符
%x 十六进制 2a
%b 布尔值 true
%tF 日期(YYYY-MM-DD) 2024-01-01

1.12 其他方法

方法 返回值 说明
intern() String 返回字符串常量池中的引用
repeat(int count) String 重复拼接(Java 11+)
indent(int n) String 每行增加 n 个空格缩进,负数减少缩进(Java 12+)
lines() Stream<String> 按行分割为流(Java 11+)
matches(String regex) boolean 整个字符串是否匹配正则
toCharArray() char[] 转为字符数组
valueOf(...) static String 将其他类型转为字符串
"Abc".repeat(3);               // "AbcAbcAbc"
"abc".intern();
"a\nb\nc".lines().count();     // 3
"123".matches("\\d+");         // true
String.valueOf(123);           // "123"
String.valueOf(true);          // "true"

valueOf 重载:boolean, char, char[], char[],offset,count, double, float, int, long, Object


2. StringBuilder / StringBuffer

特性 StringBuilder StringBuffer
线程安全 ✅ (synchronized)
性能
推荐场景 单线程 多线程

2.1 构造方法

new StringBuilder();               // 初始容量 16
new StringBuilder(int capacity);   // 指定初始容量
new StringBuilder(String str);     // 初始内容为 str,容量 = str.length() + 16
new StringBuilder(CharSequence cs);

2.2 常用方法

方法 返回值 说明
append(Xxx x) this 追加。重载覆盖所有基本类型、String、Object、char[] 等
insert(int offset, Xxx x) this 在指定位置插入
delete(int start, int end) this 删除 [start, end)
deleteCharAt(int index) this 删除指定位置的字符
replace(int start, int end, String str) this 替换区间
reverse() this 反转内容
setCharAt(int index, char ch) void 设置指定位置的字符
setLength(int newLength) void 设置长度(截断或填充 '\0')
charAt(int index) char 获取指定位置字符
indexOf(String str) int 查找子串
lastIndexOf(String str) int 反向查找子串
substring(int start) String 提取子串(返回新 String)
substring(int start, int end) String 提取子串(返回新 String)
length() int 返回当前长度
capacity() int 返回当前容量
ensureCapacity(int minimumCapacity) void 确保最小容量
trimToSize() void 将容量缩小到当前长度
toString() String 转为 String
compareTo(StringBuilder another) int 字典序比较(Java 11+)
StringBuilder sb = new StringBuilder("hello");
sb.append(" world")               // "hello world"
  .insert(5, ",")                 // "hello, world"
  .delete(5, 6)                   // "hello world"
  .reverse();                     // "dlrow olleh"

3. 包装类 (Wrapper Classes)

3.1 概览

基本类型 包装类 字节数
byte Byte 1
short Short 2
int Integer 4
long Long 8
float Float 4
double Double 8
char Character 2(无符号)
boolean Boolean

3.2 通用方法

Integer 为例:

方法 返回值 说明
parseInt(String s) static int 字符串解析为基本类型
parseInt(String s, int radix) static int 按进制解析
valueOf(String s) static Integer 字符串转为包装对象(享元缓存)
valueOf(int i) static Integer 基本类型转为包装对象(缓存 -128~127)
toString() String 转为字符串
toString(int i) static String 静态转换
toString(int i, int radix) static String 按进制转换
compare(int x, int y) static int 比较两个值
compareTo(Integer another) int 实例比较
intValue() / longValue() / doubleValue() 对应类型 转为对应基本类型
MAX_VALUE / MIN_VALUE static final 常量
SIZE / BYTES static final 位数 / 字节数
toBinaryString(int i) / toHexString(int i) / toOctalString(int i) static String 进制转换
int n = Integer.parseInt("42");           // 42
int n2 = Integer.parseInt("ff", 16);      // 255
Integer i = Integer.valueOf(127);         // 缓存对象
Integer j = Integer.valueOf(127);         // 同一对象 (i == j)
String hex = Integer.toHexString(255);    // "ff"
int max = Integer.MAX_VALUE;              // 2147483647

3.3 Character 类特有方法

方法 说明
isDigit(char ch) 是否为数字
isLetter(char ch) 是否为字母
isLetterOrDigit(char ch) 是否为字母或数字
isLowerCase(char ch) / isUpperCase(char ch) 大小写判断
isWhitespace(char ch) 是否为空白字符
toLowerCase(char ch) / toUpperCase(char ch) 大小写转换
isJavaIdentifierStart(char ch) Java 标识符首字符判断
isJavaIdentifierPart(char ch) Java 标识符其他字符判断

3.4 自动装箱/拆箱

Integer a = 100;        // 自动装箱 → Integer.valueOf(100)
int b = a;              // 自动拆箱 → a.intValue()
Integer c = null;
int d = c;              // NullPointerException!

4. Math 类

java.lang.Math — 基本数学运算。全部为静态方法。

4.1 常量

常量
Math.PI 3.141592653589793
Math.E 2.718281828459045

4.2 取舍与近似

方法 返回值 说明
abs(x) 同类型 绝对值(重载 int / long / float / double)
ceil(double a) double 向上取整
floor(double a) double 向下取整
round(double a) long 四舍五入
round(float a) int 四舍五入
rint(double a) double 取最接近整数(偶数偏好)
Math.ceil(3.14);   // 4.0
Math.floor(3.14);  // 3.0
Math.round(3.5);   // 4
Math.round(3.4);   // 3
Math.rint(2.5);    // 2.0  (偶数偏好)
Math.rint(3.5);    // 4.0  (偶数偏好)

4.3 最值

方法 说明
max(x, y) 最大值(重载 int / long / float / double)
min(x, y) 最小值
clamp(long value, long min, long max) 钳位到 [min, max](Java 21+)

4.4 幂、根、对数

方法 说明
pow(double a, double b) a 的 b 次幂
sqrt(double a) 平方根
cbrt(double a) 立方根
exp(double a) e 的 a 次幂
log(double a) 自然对数 (ln)
log10(double a) 以 10 为底的对数
log1p(double x) ln(1 + x),对小 x 更精确
Math.pow(2, 10);    // 1024.0
Math.sqrt(16);      // 4.0
Math.cbrt(27);      // 3.0
Math.log(Math.E);   // 1.0
Math.log10(100);    // 2.0

4.5 三角函数

所有角度参数单位为弧度

方法 说明
sin(double a) 正弦
cos(double a) 余弦
tan(double a) 正切
asin(double a) 反正弦
acos(double a) 反余弦
atan(double a) 反正切
atan2(double y, double x) y/x 的反正切
toDegrees(double angrad) 弧度转角度
toRadians(double angdeg) 角度转弧度

4.6 随机数与符号

方法 说明
random() 返回 [0.0, 1.0) 的随机 double
signum(double d) 符号函数:-1.0 / 0.0 / 1.0
copySign(double magnitude, double sign) 返回带符号的值
floorDiv(int x, int y) 向负无穷方向的整数除法
floorMod(int x, int y) 向负无穷方向的取模
multiplyExact(int x, int y) 乘法(溢出抛异常)
addExact(int x, int y) 加法(溢出抛异常)
subtractExact(int x, int y) 减法(溢出抛异常)
negateExact(int a) 取反(溢出抛异常)
Math.random();                       // 0.0 ~ 0.999...
int dice = (int)(Math.random() * 6) + 1;  // 1 ~ 6
Math.floorMod(-1, 5);                // 4 (而 -1 % 5 = -1)
Math.multiplyExact(Integer.MAX_VALUE, 2); // throws ArithmeticException

5. Arrays 工具类

java.util.Arrays — 数组操作工具类。

5.1 排序

方法 说明
sort(byte[] a) 原地排序(Dual-Pivot Quicksort)
sort(T[] a, Comparator<? super T> c) 使用比较器排序
sort(int[] a, int fromIndex, int toIndex) 区间排序
parallelSort(int[] a) 并行排序(大数组更快)
int[] arr = {3, 1, 4, 1, 5};
Arrays.sort(arr);                          // [1, 1, 3, 4, 5]
Arrays.sort(strArr, Comparator.reverseOrder());

5.2 查找

方法 说明
binarySearch(int[] a, int key) 二分查找。前提:数组已排序。找到返回索引;未找到返回 -(插入点 + 1)
int[] arr = {1, 3, 5, 7, 9};
int idx = Arrays.binarySearch(arr, 5);     // 2
int idx2 = Arrays.binarySearch(arr, 4);    // -3 (插入点为索引2,-2-1 = -3)

5.3 比较与填充

方法 说明
equals(int[] a, int[] a2) 比较数组内容是否相同
deepEquals(Object[] a1, Object[] a2) 深度比较(递归比较嵌套数组)
compare(int[] a, int[] a2) 字典序比较(Java 9+)
mismatch(int[] a, int[] a2) 返回首次不同位置,完全相同时返回 -1(Java 9+)
fill(int[] a, int val) 用 val 填充整个数组
fill(int[] a, int fromIndex, int toIndex, int val) 区间填充
setAll(int[] a, IntUnaryOperator gen) 按索引生成填充值
hashCode(int[] a) 数组哈希码
deepHashCode(Object[] a) 深度哈希

5.4 转换

方法 说明
toString(int[] a) 数组的字符串表示 "[1, 2, 3]"
deepToString(Object[] a) 深度字符串表示
asList(T... a) 返回固定大小的 List 视图
copyOf(int[] a, int newLength) 拷贝并调整长度(截断或补零)
copyOfRange(int[] a, int from, int to) 拷贝区间 [from, to)
stream(int[] a) 返回 IntStream
stream(T[] a) 返回 Stream<T>
stream(int[] a, int startInclusive, int endExclusive) 区间流
String[] strs = {"a", "b", "c"};
List<String> list = Arrays.asList(strs);
list.set(0, "x");        // OK, 数组同步变为 ["x", "b", "c"]
list.add("d");           // UnsupportedOperationException! 固定大小

int[] copy = Arrays.copyOf(new int[]{1,2,3}, 5);   // [1, 2, 3, 0, 0]
int[] range = Arrays.copyOfRange(new int[]{1,2,3,4,5}, 1, 4); // [2, 3, 4]

6. ArrayList

java.util.ArrayList<E> — 基于数组的动态列表,随机访问 O(1),插入/删除 O(n)。

6.1 构造方法

new ArrayList<>();                   // 默认容量 10
new ArrayList<>(int initialCapacity);
new ArrayList<>(Collection<? extends E> c);

6.2 增删改查

方法 返回值 说明
add(E e) boolean 追加到末尾(始终返回 true)
add(int index, E element) void 在指定位置插入
addAll(Collection<? extends E> c) boolean 追加全部
addAll(int index, Collection<? extends E> c) boolean 在指定位置插入全部
get(int index) E 获取指定位置元素
set(int index, E element) E 替换指定位置元素,返回旧值
remove(int index) E 移除指定位置元素,返回被移除元素
remove(Object o) boolean 移除第一个匹配的元素
removeAll(Collection<?> c) boolean 移除集合中包含的全部元素(差集)
retainAll(Collection<?> c) boolean 仅保留集合中包含的元素(交集)
removeIf(Predicate<? super E> filter) boolean 条件删除
clear() void 清空
list.remove(1);       // 按索引
list.remove(Integer.valueOf(1));  // 按值
list.removeIf(s -> s.startsWith("A"));

6.3 查询

方法 返回值 说明
size() int 元素数量
isEmpty() boolean 是否为空
contains(Object o) boolean 是否包含
containsAll(Collection<?> c) boolean 是否包含全部
indexOf(Object o) int 首次出现的位置
lastIndexOf(Object o) int 最后出现的位置

6.4 迭代与转换

方法 返回值 说明
iterator() Iterator<E> 获取迭代器
listIterator() ListIterator<E> 获取列表迭代器(可双向遍历)
listIterator(int index) ListIterator<E> 从指定位置开始的列表迭代器
forEach(Consumer<? super E> action) void 遍历(Iterable 默认方法)
toArray() Object[] 转为 Object 数组
toArray(T[] a) T[] 转为指定类型数组
subList(int fromIndex, int toIndex) List<E> 返回视图,修改视图影响原列表
// 转数组推荐写法
String[] arr = list.toArray(new String[0]);

// subList 陷阱
List<Integer> sub = list.subList(0, 3);
sub.clear();  // 原 list 的前 3 个元素也被删除!

6.5 其他

方法 说明
ensureCapacity(int minCapacity) 确保最小容量(减少扩容次数)
trimToSize() 将容量缩小到当前 size
sort(Comparator<? super E> c) 排序(List 接口默认方法)
replaceAll(UnaryOperator<E> operator) 逐个替换

7. LinkedList

java.util.LinkedList<E> — 双向链表。实现了 List<E>Deque<E>

7.1 Deque 方法(用作栈/队列)

方法 说明
addFirst(E e) / addLast(E e) 在首/尾添加
offerFirst(E e) / offerLast(E e) 在首/尾添加(容量受限时返回 false)
removeFirst() / removeLast() 移除并返回首/尾(空时抛异常)
pollFirst() / pollLast() 移除并返回首/尾(空时返回 null)
getFirst() / getLast() 查看首/尾(空时抛异常)
peekFirst() / peekLast() 查看首/尾(空时返回 null)
removeFirstOccurrence(Object o) 移除首次出现
removeLastOccurrence(Object o) 移除最后出现
// 作为栈 (LIFO)
LinkedList<String> stack = new LinkedList<>();
stack.push("a");          // addFirst
stack.push("b");
stack.pop();              // "b" (removeFirst)

// 作为队列 (FIFO)
LinkedList<String> queue = new LinkedList<>();
queue.offer("a");         // addLast
queue.offer("b");
queue.poll();             // "a" (removeFirst)

8. HashSet

java.util.HashSet<E> — 基于 HashMap 的集合,O(1) 增删查,无序。

方法 返回值 说明
add(E e) boolean 添加元素(已存在时返回 false)
remove(Object o) boolean 移除元素
contains(Object o) boolean 是否包含
size() int 元素数量
isEmpty() boolean 是否为空
clear() void 清空
iterator() Iterator<E> 迭代器

构造时可传入 initialCapacityloadFactor

注意:自定义对象存入 HashSet 必须正确重写 equals()hashCode()


9. HashMap

java.util.HashMap<K, V> — 哈希表实现,键值对,O(1) 增删查。

9.1 构造方法

new HashMap<>();                          // 默认容量 16,负载因子 0.75
new HashMap<>(int initialCapacity);
new HashMap<>(int initialCapacity, float loadFactor);
new HashMap<>(Map<? extends K, ? extends V> m);

9.2 增删改查

方法 返回值 说明
put(K key, V value) V 添加或覆盖,返回旧值
putIfAbsent(K key, V value) V 仅键不存在时添加,返回当前值
putAll(Map<? extends K, ? extends V> m) void 批量添加
get(Object key) V 获取值(不存在返回 null)
getOrDefault(Object key, V defaultValue) V 获取值或默认值
remove(Object key) V 移除键值对,返回被移除的值
remove(Object key, Object value) boolean 仅键值都匹配时才移除
replace(K key, V value) V 仅键存在时替换
replace(K key, V oldValue, V newValue) boolean 仅键和旧值都匹配时替换
replaceAll(BiFunction<? super K,? super V,? extends V> function) void 批量替换
clear() void 清空

9.3 查询

方法 返回值 说明
containsKey(Object key) boolean 是否包含键
containsValue(Object value) boolean 是否包含值(O(n))
size() int 键值对数量
isEmpty() boolean 是否为空

9.4 迭代

方法 返回值 说明
keySet() Set<K> 所有键的视图,修改影响原 Map
values() Collection<V> 所有值的视图
entrySet() Set<Map.Entry<K, V>> 键值对视图
forEach(BiConsumer<? super K, ? super V> action) void 遍历
// 推荐遍历方式
for (Map.Entry<K, V> entry : map.entrySet()) {
    K key = entry.getKey();
    V value = entry.getValue();
}

// Lambda 遍历
map.forEach((k, v) -> System.out.println(k + " = " + v));

9.5 计算

方法 说明
compute(K key, BiFunction<? super K,? super V,? extends V> remapping) 计算新值(键不存在时 value 参数为 null)
computeIfAbsent(K key, Function<? super K,? extends V> mapping) 不存在时计算并存入
computeIfPresent(K key, BiFunction<? super K,? super V,? extends V> remapping) 存在时计算并存入
merge(K key, V value, BiFunction<? super V,? super V,? extends V> remapping) 合并(键不存在直接放;存在则用函数合并)
// 计数
map.merge(word, 1, Integer::sum);

// 分组
map.computeIfAbsent(key, k -> new ArrayList<>()).add(item);

9.6 Map.Entry 方法

方法 说明
getKey() 获取键
getValue() 获取值
setValue(V value) 设置新值

10. Stream API

java.util.stream.Stream<T> — 函数式流操作。

10.1 创建流

// 从集合
collection.stream();
collection.parallelStream();

// 从数组
Arrays.stream(arr);
Stream.of(array);

// 直接创建
Stream.of("a", "b", "c");
Stream.iterate(0, n -> n + 1);              // 无限流
Stream.iterate(0, n -> n < 100, n -> n + 1); // 有限流(Java 9+)
Stream.generate(Math::random);              // 无限流
Stream.<String>builder().add("a").add("b").build();

// 基本类型流(避免装箱)
IntStream.range(1, 10);       // [1, 10)
IntStream.rangeClosed(1, 10); // [1, 10]
LongStream, DoubleStream 同理

10.2 中间操作(惰性,返回 Stream)

方法 说明
filter(Predicate<? super T> predicate) 过滤
map(Function<? super T, ? extends R> mapper) 一对一映射
flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) 一对多映射并展平
mapToInt(ToIntFunction<? super T> mapper) 映射为 IntStream
mapToLong() / mapToDouble() 映射为基本类型流
distinct() 去重(基于 equals)
sorted() 自然排序
sorted(Comparator<? super T> comparator) 指定比较器排序
peek(Consumer<? super T> action) 调试用,对流中每个元素执行操作
limit(long maxSize) 截取前 n 个
skip(long n) 跳过前 n 个
takeWhile(Predicate<? super T> predicate) 取满足条件的元素,直到第一个不满足(Java 9+)
dropWhile(Predicate<? super T> predicate) 跳过满足条件的元素,保留剩余(Java 9+)
boxed() 基本类型流转为包装类型流

10.3 终端操作

方法 返回值 说明
forEach(Consumer<? super T> action) void 遍历
forEachOrdered(Consumer<? super T> action) void 按顺序遍历(并行流保序)
toArray() Object[] 转为数组
toArray(IntFunction<A[]> generator) A[] 转为指定类型数组
collect(Collector<? super T,A,R> collector) R 收集
toList() List<T> 转为不可变列表(Java 16+)
reduce(T identity, BinaryOperator<T> accumulator) T 归约
reduce(BinaryOperator<T> accumulator) Optional<T> 归约(无初始值)
count() long 计数
min(Comparator<? super T> comparator) Optional<T> 最小值
max(Comparator<? super T> comparator) Optional<T> 最大值
anyMatch(Predicate<? super T> predicate) boolean 任一匹配
allMatch(Predicate<? super T> predicate) boolean 全部匹配
noneMatch(Predicate<? super T> predicate) boolean 无一匹配
findFirst() Optional<T> 第一个元素
findAny() Optional<T> 任意元素(并行流更高效)

基本类型流特有:

方法 返回值 说明
sum() int/long/double 求和
average() OptionalDouble 平均值
summaryStatistics() IntSummaryStatistics 统计信息(count, sum, min, max, avg)

10.4 Collectors 常用方法

java.util.stream.Collectors

方法 说明
toList() 收集到 List
toSet() 收集到 Set
toMap(keyMapper, valueMapper) 收集到 Map(键冲突抛异常)
toMap(keyMapper, valueMapper, mergeFunction) 收集到 Map(指定冲突处理)
toMap(keyMapper, valueMapper, mergeFunction, mapSupplier) 指定 Map 实现
toCollection(Supplier<C>) 收集到指定集合
joining() 连接为字符串
joining(CharSequence delimiter) 带分隔符连接
joining(CharSequence delimiter, prefix, suffix) 带前后缀
groupingBy(Function) 分组到 Map<K, List<V>>
groupingBy(Function, downstream) 分组 + 下游收集器
partitioningBy(Predicate) 按条件分区 Map<Boolean, List<V>>
counting() 计数
summarizingInt(ToIntFunction) 统计
summingInt/maxBy/minBy/averagingInt 数值聚合
reducing(BinaryOperator) 归约
mapping(Function, downstream) 先映射再收集
flatMapping(Function, downstream) 先 flatMap 再收集(Java 9+)
filtering(Predicate, downstream) 先过滤再收集(Java 9+)
teeing(downstream1, downstream2, merger) 双下游合并(Java 12+)
// 分组计数
Map<String, Long> count = list.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

// 分组为 List
Map<String, List<Item>> groups = items.stream()
    .collect(Collectors.groupingBy(Item::getCategory));

// toMap 冲突处理
Map<Integer, String> map = items.stream()
    .collect(Collectors.toMap(Item::getId, Item::getName, (old, n) -> old));

// joining
String result = list.stream().collect(Collectors.joining(", ", "[", "]"));
// "[a, b, c]"

// teeing(同时求平均分和总分)
record Stats(double avg, int sum) {}
Stats stats = scores.stream()
    .collect(Collectors.teeing(
        Collectors.averagingInt(Integer::intValue),
        Collectors.summingInt(Integer::intValue),
        Stats::new
    ));

11. Optional 类

java.util.Optional<T> — 容器对象,避免空指针。

11.1 创建

方法 说明
Optional.empty() 空 Optional
Optional.of(T value) 非空值(value 为 null 时抛 NPE)
Optional.ofNullable(T value) 可为 null 的值(null → empty)
Optional<String> opt = Optional.of("hello");
Optional<String> empty = Optional.empty();
Optional<String> nullable = Optional.ofNullable(maybeNull);

11.2 获取值

方法 返回值 说明
get() T 获取值(空时抛 NoSuchElementException)
orElse(T other) T 有值返回值,无值返回 other
orElseGet(Supplier<? extends T> supplier) T 有值返回值,无值调用 supplier
orElseThrow() T 有值返回值,无值抛 NoSuchElementException(Java 10+)
orElseThrow(Supplier<? extends X> exceptionSupplier) T 有值返回值,无值抛指定异常
or(Supplier<? extends Optional<? extends T>> supplier) Optional<T> 有值返回自身,无值返回 supplier 提供的 Optional(Java 9+)
// 推荐
String s = opt.orElse("default");
String s2 = opt.orElseGet(() -> computeDefault());   // 惰性,无值时再计算
String s3 = opt.orElseThrow(() -> new IllegalArgumentException("missing"));

11.3 判断

方法 返回值 说明
isPresent() boolean 是否有值
isEmpty() boolean 是否为空(Java 11+)

11.4 转换与过滤

方法 返回值 说明
map(Function<? super T, ? extends U> mapper) Optional<U> 有值则映射
flatMap(Function<? super T, ? extends Optional<? extends U>> mapper) Optional<U> 有值则映射并展平
filter(Predicate<? super T> predicate) Optional<T> 有值且满足条件则保留,否则返回 empty
ifPresent(Consumer<? super T> action) void 有值时执行
ifPresentOrElse(Consumer<? super T> action, Runnable emptyAction) void 有值执行 action,否则执行 emptyAction(Java 9+)
stream() Stream<T> 有值时为单元素流,空时为(Java 9+)
// 链式调用
String result = Optional.ofNullable(user)
    .map(User::getAddress)
    .map(Address::getCity)
    .filter(city -> !city.isBlank())
    .orElse("Unknown");

// ifPresentOrElse
opt.ifPresentOrElse(
    v -> System.out.println("Found: " + v),
    () -> System.out.println("Not found")
);

12. Collections 工具类

java.util.Collections — 集合操作工具类。

12.1 排序与搜索

方法 说明
sort(List<T> list) 自然排序
sort(List<T> list, Comparator<? super T> c) 指定比较器排序
reverse(List<?> list) 反转顺序
shuffle(List<?> list) 随机打乱
shuffle(List<?> list, Random rnd) 指定随机源打乱
swap(List<?> list, int i, int j) 交换两个位置
fill(List<? super T> list, T obj) 填充
binarySearch(List<? extends Comparable<? super T>> list, T key) 二分查找
binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 带比较器的二分查找
min(Collection<? extends T> coll) 自然序最小值
max(Collection<? extends T> coll) 自然序最大值
min(Collection<? extends T> coll, Comparator<? super T> comp) 指定比较器最小值
max(Collection<? extends T> coll, Comparator<? super T> comp) 指定比较器最大值

12.2 同步与不可变包装

方法 说明
synchronizedList(List<T> list) 返回线程安全的 List
synchronizedSet(Set<T> s) 返回线程安全的 Set
synchronizedMap(Map<K,V> m) 返回线程安全的 Map
synchronizedCollection(Collection<T> c) 返回线程安全的 Collection
unmodifiableList(List<? extends T> list) 返回不可修改的 List 视图
unmodifiableSet(Set<? extends T> s) 返回不可修改的 Set 视图
unmodifiableMap(Map<? extends K, ? extends V> m) 返回不可修改的 Map 视图
unmodifiableCollection(Collection<? extends T> c) 返回不可修改的 Collection 视图

12.3 其他

方法 说明
copy(List<? super T> dest, List<? extends T> src) 拷贝 src 到 dest
frequency(Collection<?> c, Object o) 出现频率
disjoint(Collection<?> c1, Collection<?> c2) 无交集时返回 true
addAll(Collection<? super T> c, T... elements) 添加可变参数
replaceAll(List<T> list, T oldVal, T newVal) 替换所有出现
rotate(List<?> list, int distance) 轮转(distance > 0 向右)
indexOfSubList(List<?> source, List<?> target) 子列表首次出现位置
nCopies(int n, T o) 返回包含 n 份 o 的不可变列表
singleton(T o) 返回包含单个元素的不可变 Set
singletonList(T o) 返回包含单个元素的不可变 List
singletonMap(K key, V value) 返回包含单个键值对的不可变 Map
emptyList() / emptySet() / emptyMap() 返回空不可变集合
checkedList(...) / checkedSet(...) / checkedMap(...) 返回运行时类型检查包装

13. LocalDate / LocalTime / LocalDateTime

java.time.* — Java 8+ 日期时间 API。

13.1 创建

// 当前时间
LocalDate.now();                          // 当前日期
LocalTime.now();                          // 当前时间
LocalDateTime.now();                      // 当前日期时间
ZonedDateTime.now();                      // 带时区
Instant.now();                            // UTC 时间戳

// 指定值
LocalDate.of(2024, 1, 15);                // 2024-01-15
LocalTime.of(14, 30, 0);                  // 14:30:00
LocalDateTime.of(2024, 1, 15, 14, 30, 0);

// 解析
LocalDate.parse("2024-01-15");
LocalTime.parse("14:30:00");
LocalDateTime.parse("2024-01-15T14:30:00");

// 自定义格式
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd");
LocalDate.parse("2024/01/15", fmt);

13.2 LocalDate 常用方法

方法 返回值 说明
getYear() int 年份
getMonth() Month 月份枚举
getMonthValue() int 月份值 (1–12)
getDayOfMonth() int 月中日期 (1–31)
getDayOfWeek() DayOfWeek 星期几枚举
getDayOfYear() int 年中天数 (1–365/366)
lengthOfMonth() int 当月天数
lengthOfYear() int 当年天数 (365/366)
isLeapYear() boolean 是否闰年
plusDays(long n) LocalDate +n 天
plusWeeks(long n) LocalDate +n 周
plusMonths(long n) LocalDate +n 月
plusYears(long n) LocalDate +n 年
minusDays(long n) LocalDate -n 天
minusWeeks(long n) LocalDate -n 周
minusMonths(long n) LocalDate -n 月
minusYears(long n) LocalDate -n 年
withDayOfMonth(int dayOfMonth) LocalDate 设置月中日
withMonth(int month) LocalDate 设置月
withYear(int year) LocalDate 设置年
with(TemporalAdjuster adjuster) LocalDate 使用调节器
isAfter(ChronoLocalDate other) boolean 是否在之后
isBefore(ChronoLocalDate other) boolean 是否在之前
isEqual(ChronoLocalDate other) boolean 是否相等
until(LocalDate endExclusive, PeriodUnit unit) long 到指定日期的单位数量
format(DateTimeFormatter formatter) String 格式化为字符串

13.3 Timeline 常用方法

方法 返回值 说明
getHour() / getMinute() / getSecond() / getNano() int 时/分/秒/纳秒
plusHours(long n) / plusMinutes(long n) / plusSeconds(long n) LocalTime 时间加减
isBefore(LocalTime other) / isAfter(LocalTime other) boolean 时间比较

13.4 LocalDateTime

LocalDateTime 是 LocalDate + LocalTime 的组合,两边的操作都支持:

LocalDateTime dt = LocalDateTime.now();
dt.toLocalDate();      // 提取日期部分
dt.toLocalTime();      // 提取时间部分
dt.atZone(ZoneId.systemDefault());    // 添加时区 → ZonedDateTime
dt.toInstant(ZoneOffset.UTC);         // 转 UTC Instant

13.5 TemporalAdjusters 常用调节器

import static java.time.temporal.TemporalAdjusters.*;

localDate.with(firstDayOfMonth());        // 当月第一天
localDate.with(lastDayOfMonth());         // 当月最后一天
localDate.with(firstDayOfNextMonth());    // 下月第一天
localDate.with(firstDayOfYear());         // 当年第一天
localDate.with(lastDayOfYear());          // 当年最后一天
localDate.with(next(DayOfWeek.MONDAY));   // 下一个周一
localDate.with(previous(DayOfWeek.MONDAY)); // 上一个周一
localDate.with(dayOfWeekInMonth(2, DayOfWeek.MONDAY)); // 本月第二个周一

13.6 DateTimeFormatter 常用模式

模式字符 含义 示例输出
y 2024, 24
M 01, 1, Jan
d 05, 5
H 时 (0–23) 14, 09
h 时 (1–12) 02
m 30
s 00
S 毫秒 123
a 上下午 AM, PM
E 星期 Tue, Tuesday
z 时区 CST, China Standard Time
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");  // 2024-01-15 14:30:00
DateTimeFormatter.ofPattern("yyyy年MM月dd日 E");      // 2024年01月15日 星期一
DateTimeFormatter.ISO_LOCAL_DATE;                    // 2024-01-15

13.7 Duration 与 Period

用途 示例
Duration 时间间隔(时分秒纳秒) Duration.between(startTime, endTime)
Period 日期间隔(年月日) Period.between(startDate, endDate)
Duration d = Duration.ofMinutes(30);
Duration.between(Instant t1, Instant t2).toMillis();

Period p = Period.ofMonths(3);
Period.between(date1, date2).getDays();

14. File / Path / Files

java.io.File(旧)和 java.nio.file.*(Java 7+ NIO.2)。

14.1 Path 创建

Path p = Path.of("/home", "user", "doc.txt");        // Java 11+
Path p = Paths.get("/home", "user", "doc.txt");       // Java 7+
Path p = Path.of("/home/user/doc.txt");
Path p = Path.of("docs").resolve("readme.md");        // docs/readme.md
Path p = Path.of(".").toAbsolutePath().normalize();   // 规范化绝对路径

14.2 Files 常用静态方法

文件/目录检查

方法 返回值 说明
exists(Path path, LinkOption... options) boolean 是否存在
notExists(Path path, LinkOption... options) boolean 是否不存在
isDirectory(Path path, LinkOption... options) boolean 是否目录
isRegularFile(Path path, LinkOption... options) boolean 是否普通文件
isReadable(Path path) boolean 是否可读
isWritable(Path path) boolean 是否可写
isExecutable(Path path) boolean 是否可执行
isHidden(Path path) boolean 是否隐藏
size(Path path) long 文件大小(字节)
isSameFile(Path path, Path path2) boolean 是否同一文件

读/写

方法 返回值 说明
readString(Path path) String 读取全部文本(UTF-8,Java 11+)
readString(Path path, Charset cs) String 指定编码读取
writeString(Path path, CharSequence cs, OpenOption... options) Path 写入文本(Java 11+)
readAllLines(Path path) List<String> 读取所有行
readAllLines(Path path, Charset cs) List<String> 指定编码读取所有行
readAllBytes(Path path) byte[] 读取全部字节
write(Path path, byte[] bytes, OpenOption... options) Path 写入字节
lines(Path path) Stream<String> 延迟读取行流(需要 close
newBufferedReader(Path path) BufferedReader 缓冲读取
newBufferedWriter(Path path, OpenOption... options) BufferedWriter 缓冲写入
newInputStream(Path path, OpenOption... options) InputStream 输入流
newOutputStream(Path path, OpenOption... options) OutputStream 输出流
// 简洁读写
String content = Files.readString(Path.of("file.txt"));
Files.writeString(Path.of("file.txt"), "Hello World");

// try-with-resources 流式读取
try (Stream<String> lines = Files.lines(Path.of("large.txt"))) {
    lines.filter(s -> s.startsWith("ERROR")).forEach(System.out::println);
}

目录与文件操作

方法 返回值 说明
createDirectory(Path dir, FileAttribute<?>... attrs) Path 创建目录
createDirectories(Path dir, FileAttribute<?>... attrs) Path 创建所有不存在的父目录
createFile(Path path, FileAttribute<?>... attrs) Path 创建文件
createTempFile(Path dir, String prefix, String suffix, FileAttribute<?>... attrs) Path 创建临时文件
createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) Path 系统临时目录中创建
createTempDirectory(...) Path 创建临时目录
copy(Path source, Path target, CopyOption... options) Path 复制
move(Path source, Path target, CopyOption... options) Path 移动/重命名
delete(Path path) void 删除(不存在抛异常)
deleteIfExists(Path path) boolean 删除(不存在返回 false)
list(Path dir) Stream<Path> 列出目录内容(一层)
walk(Path start, FileVisitOption... options) Stream<Path> 深度优先遍历目录树
walk(Path start, int maxDepth, FileVisitOption... options) Stream<Path> 指定遍历深度
find(Path start, int maxDepth, BiPredicate<Path,BasicFileAttributes> matcher, FileVisitOption... options) Stream<Path> 条件查找
// 同时复制内容、属性和覆盖
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);

// 查找目录下所有 .java 文件
try (Stream<Path> walk = Files.walk(Path.of("src"))) {
    walk.filter(p -> p.toString().endsWith(".java")).forEach(System.out::println);
}

文件属性

方法 返回值 说明
getLastModifiedTime(Path path, LinkOption... options) FileTime 最后修改时间
setLastModifiedTime(Path path, FileTime time) Path 设置最后修改时间
getOwner(Path path, LinkOption... options) UserPrincipal 文件所有者
getPosixFilePermissions(Path path, LinkOption... options) Set<PosixFilePermission> POSIX 权限
readAttributes(Path path, String attributes, LinkOption... options) Map<String,Object> 读取属性
probeContentType(Path path) String 探测 MIME 类型
Map<String, Object> attrs = Files.readAttributes(path, "size,lastModifiedTime,isDirectory");
long size = (long) attrs.get("size");

14.3 旧 File 类(兼容参考)

方法 说明
File(String pathname) 构造
exists() / isFile() / isDirectory() 检查
getName() / getPath() / getAbsolutePath() 路径信息
length() 文件大小
lastModified() 最后修改时间(毫秒时间戳)
list() / listFiles() 列出子文件
mkdir() / mkdirs() 创建目录
renameTo(File dest) 重命名
delete() 删除
toPath() 转为 Path
createNewFile() 创建新文件

15. Objects 工具类

java.util.Objects — Object 静态工具类。

方法 返回值 说明
equals(Object a, Object b) boolean null 安全比较
deepEquals(Object a, Object b) boolean 深度 equals
hash(Object... values) int 生成哈希码
hashCode(Object o) int null 安全 hash(null → 0)
toString(Object o) String null 安全 toString(null → "null")
toString(Object o, String nullDefault) String null 安全 toString(null → 自定义)
requireNonNull(T obj) T null 抛 NullPointerException
requireNonNull(T obj, String message) T null 抛带消息的 NPE
requireNonNull(T obj, Supplier<String> messageSupplier) T null 抛 NPE(惰性消息)
requireNonNullElse(T obj, T defaultObj) T null 时返回默认值(Java 9+)
requireNonNullElseGet(T obj, Supplier<? extends T> supplier) T null 时调用 supplier(Java 9+)
isNull(Object obj) boolean 是否为 null
nonNull(Object obj) boolean 是否非 null
checkIndex(int index, int length) int 检查索引是否在 [0, length)(Java 9+)
checkFromIndexSize(int fromIndex, int size, int length) int 检查子区间(Java 9+)
checkFromToIndex(int fromIndex, int toIndex, int length) int 检查区间(Java 9+)
Objects.equals(null, null);          // true
Objects.hash("a", 1, null);          // 安全哈希
Objects.toString(obj, "N/A");        // 空值友好
Objects.requireNonNull(param, "param must not be null");

参考资料

  • Java 17 API Specification
  • 本文格式说明:返回值 列中标记 static 表示静态方法;返回值为 this 表示返回当前实例(支持链式调用)。

本文档于 2026/05 基于 Java 17 LTS 整理。