字符串相关操作


一、字符串生成与分割

  1. split(regex)
    按正则表达式分割字符串,支持限制分割次数

    1
    2
    3
    String str = "a,b,c";
    String[] arr1 = str.split(","); // ["a","b","c"]
    String[] arr2 = str.split(",", 2); // ["a","b,c"]
  2. String.join(delimiter, elements) (Java 8+)
    用指定分隔符连接字符串集合

    1
    2
    List<String> list = Arrays.asList("Java", "Python", "C++");
    String joined = String.join(" | ", list); // "Java | Python | C++"

二、字符串连接与构建

  1. concat(String str)
    字符串拼接(等价于 + 运算符)

    1
    String s = "Hello".concat(" World"); // "Hello World"
  2. StringJoiner (Java 8+)
    支持前缀后缀的高级连接

    1
    2
    StringJoiner sj = new StringJoiner(",", "[", "]");
    sj.add("Apple").add("Banana"); // "[Apple,Banana]"

三、字符串查询与判断

  1. contains(CharSequence s)
    判断是否包含子串

    1
    "Hello".contains("ell"); // true
  2. indexOf(String str)
    返回首次出现的索引

    1
    "abcde".indexOf("cd"); // 2
  3. startsWith(String prefix)
    前缀检查

    1
    "file.txt".startsWith("file"); // true

四、字符串修改

  1. replace(char old, char new)
    字符替换

    1
    "hello".replace('l', 'w'); // "hewwo"
  2. replaceAll(regex, replacement)
    正则全局替换

    1
    "a1b2c3".replaceAll("\\d", "*"); // "a*b*c*"
  3. substring(int beginIndex)
    提取子串(注意索引越界)

    1
    2
    "abcdef".substring(2); // "cdef"
    "abcdef".substring(2,4); // "cd"

五、格式转换

  1. toUpperCase() / toLowerCase()
    大小写转换(注意 Locale 问题)

    1
    "Hello".toLowerCase(); // "hello"
  2. trim() / strip() (Java 11+)
    去除空白字符(strip() 支持 Unicode)

    1
    "  text  ".strip(); // "text"

六、类型转换

  1. valueOf()
    其他类型转字符串

    1
    2
    String.valueOf(123); // "123"
    String.valueOf(new char[]{'a','b'}); // "ab"
  2. toCharArray()
    转字符数组

    1
    char[] arr = "abc".toCharArray(); // ['a','b','c']

七、高级操作

  1. matches(regex)
    正则表达式匹配

    1
    "2023-01-01".matches("\\d{4}-\\d{2}-\\d{2}"); // true
  2. repeat(int count) (Java 11+)
    字符串重复

    1
    "ab".repeat(3); // "ababab"

八、其他实用方法

方法 说明 示例
length() 获取字符串长度 “Hello”.length() → 5
isEmpty() 判断空字符串 “”.isEmpty() → true
isBlank() (Java 11+) 判断空白字符串 “ “.isBlank() → true
compareTo(String) 字典序比较 “a”.compareTo(“b”) → -1

最佳实践建议

  1. 分割注意事项:使用 split("\\.") 处理点号,避免正则陷阱
  2. 拼接性能优化:循环拼接优先用 StringBuilder
  3. 空值处理str == null 时调用方法会抛 NPE,建议先判空
  4. 版本兼容isBlank()/strip() 需 Java 11+

Array List Map Set Collection相关操作

以下是针对 JDK 1.8 的集合框架核心操作总结(已移除 Java 8+ 不支持的 API):


一、Array 数组操作

1
2
3
4
5
6
7
// 创建与初始化
String[] arr = new String[]{"a", "b", "c"};

// JDK 8 关键操作
Arrays.sort(arr, (s1, s2) -> s2.compareTo(s1)); // 自定义排序
Arrays.stream(arr).filter(s -> !s.isEmpty()); // 流式过滤
System.arraycopy(src, 0, dest, 0, src.length); // 高效数组拷贝

二、List 列表操作(ArrayList/LinkedList)

1
2
3
4
5
6
7
8
9
List<String> list = new ArrayList<>(Arrays.asList("Java", "C++"));

// JDK 8 增强方法
list.removeIf(s -> s.length() < 4); // 条件删除
list.replaceAll(String::toUpperCase); // 批量转换
list.sort(Comparator.comparingInt(String::length)); // 链式比较器

// 不可变列表(替代 Java 9+ List.of())
List<String> unmodifiable = Collections.unmodifiableList(list);

三、Set 集合操作(HashSet/TreeSet)

1
2
3
4
5
6
7
8
9
Set<Integer> set = new HashSet<>(Arrays.asList(1,2,3));

// JDK 8 特性应用
set.removeIf(n -> n % 2 == 0); // 条件删除
set.stream().map(n -> n * 2).collect(Collectors.toSet()); // 流式转换

// 集合运算
Set<String> intersection = new HashSet<>(set1);
intersection.retainAll(set2); // 交集

四、Map 映射操作(HashMap)

1
2
3
4
5
6
7
8
9
10
11
12
Map<String, Integer> map = new HashMap<>();
map.put("age", 25);

// JDK 8 核心增强
map.computeIfAbsent("score", k -> 100); // 延迟计算
map.replaceAll((k, v) -> v + 10); // 批量更新
map.entrySet().removeIf(e -> e.getValue() < 18); // 条件删除

// 流式处理(JDK 8+)
map.entrySet().stream()
.filter(e -> e.getKey().startsWith("a"))
.forEach(System.out::println);

五、Collection 通用操作

1
2
3
4
5
6
7
8
9
10
11
// JDK 8 流式编程
collection.stream()
.filter(obj -> obj != null)
.map(Object::toString)
.collect(Collectors.toList());

// 批量操作(替代 Java 9+ 工厂方法)
List<String> fastList = new ArrayList<String>() {{ // 双括号初始化(非线程安全)
add("a");
add("b");
}};

JDK 1.8 最佳实践

  1. 流式处理优化

    1
    2
    // 并行流谨慎使用(数据量>1万时考虑)
    list.parallelStream().forEach(System.out::println);
  2. 不可变集合

    1
    2
    3
    // 使用 Guava 替代 Java 9+ API
    // import com.google.common.collect.ImmutableList;
    ImmutableList<String> immutable = ImmutableList.of("a", "b");
  3. 空安全处理

    1
    2
    // 使用 Optional 避免 NPE
    Optional.ofNullable(map.get("key")).orElse("default");
  4. 性能关键代码

    1
    2
    // 优先使用原始类型集合(避免装箱)
    IntStream.range(0, 100).toArray(); // 代替 List<Integer>
  5. 兼容性注意

    1
    2
    3
    // Arrays.asList() 返回固定大小列表
    List<String> fixedList = Arrays.asList("a", "b");
    fixedList.add("c"); // 抛出 UnsupportedOperationException

版本特性对照表

功能 JDK 8 实现方案 高版本替代方案
快速创建集合 Arrays.asList() + Guava List.of() (Java 9+)
流式结果收集 Collectors.toList() Stream.toList() (16+)
空安全遍历 Optional + ifPresent Objects.requireNonNullElse (9+)

通过结合 Lambda 表达式和 Stream API,可在 JDK 1.8 中实现高效的函数式集合操作。对于不可变集合等特性,建议使用 Guava 库补充实现。