Java 日常开发常用 API 总结与示例

Java 日常开发常用 API 总结与示例

在日常业务开发中,真正高频使用的 Java API 往往集中在 字符串、集合、Stream、Optional、日期时间、文件 IO、JSON、并发、工具类 等几类。本文按场景整理常用 API,并给出可直接参考的示例。代码以 Java 8+ 为主,部分标注 Java 9/11/17+。


一、字符串处理

1. 常用判断与转换

java 复制代码
String str = " Hello, Java ";

str.isEmpty();                 // 是否为空字符串
str.isBlank();                 // Java 11+,是否空白
str.trim();                    // 去首尾空格(旧)
str.strip();                   // Java 11+,去首尾空白
str.length();                  // 长度
str.charAt(0);                 // 指定字符
str.substring(1, 5);           // 截取
str.indexOf("Java");           // 查找位置
str.contains("Java");          // 是否包含
str.startsWith(" He");
str.endsWith(" ");
str.equalsIgnoreCase(" hello, java ");

2. 替换、分割、拼接

java 复制代码
String s = "a,b,c";

String[] arr = s.split(",");                 // 分割
String joined = String.join("-", arr);       // a-b-c
String replaced = s.replace("a", "x");       // x,b,c
String upper = s.toUpperCase();
String lower = s.toLowerCase();

String formatted = String.format("name=%s, age=%d", "Tom", 18);

3. StringBuilder / StringJoiner

循环拼接字符串时不要用 +:

java 复制代码
StringBuilder sb = new StringBuilder();
sb.append("a").append("b").append("c");
String result = sb.toString();

StringJoiner joiner = new StringJoiner(",", "[", "]");
joiner.add("a").add("b").add("c");
System.out.println(joiner); // [a,b,c]

二、集合框架

1. List 常用操作

java 复制代码
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add(1, "c");          // 指定位置插入
list.get(0);
list.set(0, "x");
list.remove("b");
list.removeIf(s -> s.startsWith("x")); // 条件删除
list.contains("a");
list.size();
list.isEmpty();
list.clear();

创建不可变集合:

java 复制代码
List<String> immutable = List.of("a", "b"); // Java 9+
List<String> empty = Collections.emptyList();

2. Map 常用操作

java 复制代码
Map<String, Integer> map = new HashMap<>();

map.put("a", 1);
map.putIfAbsent("b", 2);
map.get("a");
map.getOrDefault("c", 0);
map.containsKey("a");
map.containsValue(1);
map.remove("a");
map.keySet();
map.values();
map.entrySet();

高级默认方法:

java 复制代码
map.computeIfAbsent("list", k -> new ArrayList<>()).add("x");
map.computeIfPresent("a", (k, v) -> v + 1);
map.merge("a", 1, Integer::sum);
map.replaceAll((k, v) -> v * 2);
map.forEach((k, v) -> System.out.println(k + "=" + v));

3. Set 与 Queue

java 复制代码
Set<String> set = new HashSet<>();
set.add("a");
set.contains("a");
set.remove("a");

Deque<String> deque = new ArrayDeque<>();
deque.offerFirst("a");
deque.offerLast("b");
deque.pollFirst();
deque.pollLast();

4. Collections 与 Arrays 工具类

java 复制代码
List<Integer> nums = new ArrayList<>(List.of(3, 1, 2));

Collections.sort(nums);                 // 排序
Collections.reverse(nums);              // 反转
Collections.shuffle(nums);              // 随机打乱
Collections.max(nums);
Collections.min(nums);
Collections.frequency(nums, 1);         // 出现次数
Collections.unmodifiableList(nums);     // 不可变视图

int[] arr = {3, 1, 2};
Arrays.sort(arr);
Arrays.fill(arr, 0);
Arrays.copyOf(arr, 5);
Arrays.stream(arr).sum();

三、Stream API

Stream 是日常集合处理的利器。

1. filter / map / collect

java 复制代码
List<User> users = getUsers();

List<String> names = users.stream()
    .filter(u -> u.getAge() >= 18)
    .map(User::getName)
    .collect(Collectors.toList());

// Java 16+
List<String> names2 = users.stream()
    .filter(u -> u.getAge() >= 18)
    .map(User::getName)
    .toList();

2. 排序、去重、限制

java 复制代码
List<User> sorted = users.stream()
    .sorted(Comparator.comparing(User::getAge).reversed())
    .distinct()
    .limit(10)
    .collect(Collectors.toList());

3. 分组与统计

java 复制代码
Map<Integer, List<User>> byAge = users.stream()
    .collect(Collectors.groupingBy(User::getAge));

Map<String, Long> countByCity = users.stream()
    .collect(Collectors.groupingBy(User::getCity, Collectors.counting()));

IntSummaryStatistics stats = users.stream()
    .collect(Collectors.summarizingInt(User::getAge));

double avg = users.stream()
    .mapToInt(User::getAge)
    .average()
    .orElse(0);

4. 匹配与查找

java 复制代码
boolean anyAdult = users.stream().anyMatch(u -> u.getAge() >= 18);
boolean allAdult = users.stream().allMatch(u -> u.getAge() >= 18);
boolean noneChild = users.stream().noneMatch(u -> u.getAge() < 18);

Optional<User> first = users.stream()
    .filter(u -> u.getAge() > 30)
    .findFirst();

5. 拼接字符串

java 复制代码
String joined = users.stream()
    .map(User::getName)
    .collect(Collectors.joining(",", "[", "]"));

四、Optional

Optional 用于优雅处理 null,避免层层判空。

java 复制代码
Optional<User> optional = Optional.ofNullable(getUser());

// 存在则执行
optional.ifPresent(u -> System.out.println(u.getName()));

// 链式取值
String name = optional
    .map(User::getName)
    .filter(n -> !n.isBlank())
    .orElse("unknown");

// 不存在时抛异常
User user = optional.orElseThrow(() -> new RuntimeException("user not found"));

// Java 9+
optional.ifPresentOrElse(
    u -> System.out.println(u.getName()),
    () -> System.out.println("empty")
);

五、日期时间 API

Java 8 之后优先使用 java.time,不要再用 Date 和 SimpleDateFormat。

java 复制代码
LocalDate today = LocalDate.now();
LocalDate tomorrow = today.plusDays(1);
LocalDate nextMonth = today.plusMonths(1);

LocalTime now = LocalTime.now();
LocalDateTime dateTime = LocalDateTime.now();

boolean before = today.isBefore(tomorrow);
boolean after = tomorrow.isAfter(today);

// 日期差
Period period = Period.between(
    LocalDate.of(2024, 1, 1),
    LocalDate.of(2024, 3, 1)
);
System.out.println(period.getMonths()); // 2

// 时间差
Duration duration = Duration.between(
    LocalDateTime.now(),
    LocalDateTime.now().plusHours(2)
);
System.out.println(duration.toHours()); // 2

// 格式化与解析
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
String text = dateTime.format(fmt);
LocalDateTime parsed = LocalDateTime.parse("2024-01-01 10:00:00", fmt);

六、文件与 IO

1. Files 常用操作

java 复制代码
Path path = Path.of("data.txt");

// 写文件 Java 11+
Files.writeString(path, "hello", StandardCharsets.UTF_8);

// 读文件 Java 11+
String content = Files.readString(path, StandardCharsets.UTF_8);

// 按行读
List<String> lines = Files.readAllLines(path);

// 流式读
try (Stream<String> stream = Files.lines(path)) {
    stream.forEach(System.out::println);
}

// 目录与文件
Files.exists(path);
Files.createDirectories(Path.of("a/b/c"));
Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);
Files.move(src, dest, StandardCopyOption.ATOMIC_MOVE);
Files.deleteIfExists(path);

2. try-with-resources

java 复制代码
try (BufferedReader reader = Files.newBufferedReader(path)) {
    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

七、JSON 序列化

Jackson

java 复制代码
ObjectMapper mapper = new ObjectMapper();

String json = mapper.writeValueAsString(user);

User user = mapper.readValue(json, User.class);

List<User> users = mapper.readValue(
    json,
    new TypeReference<List<User>>() {}
);

Gson

java 复制代码
Gson gson = new Gson();

String json = gson.toJson(user);
User user = gson.fromJson(json, User.class);

// 深拷贝
User copy = gson.fromJson(gson.toJson(user), User.class);

八、工具类

1. Objects

java 复制代码
Objects.requireNonNull(obj, "obj must not be null");
Objects.equals(a, b);
Objects.hash(a, b, c);
Objects.isNull(obj);
Objects.nonNull(obj);
Objects.toString(obj, "default");

2. Apache Commons

java 复制代码
StringUtils.isBlank(str);
StringUtils.isNotBlank(str);
StringUtils.defaultIfBlank(str, "default");

CollectionUtils.isEmpty(list);
CollectionUtils.isNotEmpty(list);
CollectionUtils.union(list1, list2);

九、数学与随机

java 复制代码
Math.max(1, 2);
Math.min(1, 2);
Math.abs(-1);
Math.round(1.5);
Math.pow(2, 3);

BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
BigDecimal c = a.add(b); // 0.3

BigDecimal d = a.multiply(b);
BigDecimal e = a.divide(b, 2, RoundingMode.HALF_UP);

Random random = new Random();
int n = random.nextInt(100);

// 多线程推荐
int m = ThreadLocalRandom.current().nextInt(1, 100);

UUID uuid = UUID.randomUUID();

十、并发与异步

1. 线程池

java 复制代码
ExecutorService pool = Executors.newFixedThreadPool(4);

Future<Integer> future = pool.submit(() -> 1 + 1);
Integer result = future.get();

pool.shutdown();

2. CompletableFuture

java 复制代码
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "hello");

future.thenApply(String::toUpperCase)
      .thenAccept(System.out::println)
      .exceptionally(ex -> {
          ex.printStackTrace();
          return null;
      });

3. 并发容器与原子类

java 复制代码
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.computeIfAbsent("a", k -> 0);
map.merge("a", 1, Integer::sum);

AtomicInteger atomic = new AtomicInteger(0);
atomic.incrementAndGet();
atomic.compareAndSet(1, 2);

LongAdder adder = new LongAdder();
adder.increment();
long sum = adder.sum();

4. 同步工具

java 复制代码
CountDownLatch latch = new CountDownLatch(3);
latch.countDown();
latch.await();

Semaphore semaphore = new Semaphore(2);
semaphore.acquire();
semaphore.release();

十一、异常与资源

多异常捕获:

java 复制代码
try {
    // ...
} catch (IOException | SQLException e) {
    e.printStackTrace();
} finally {
    // 清理
}

自定义异常:

java 复制代码
public class BizException extends RuntimeException {
    public BizException(String message) {
        super(message);
    }
}

十二、系统与运行时

java 复制代码
long millis = System.currentTimeMillis();
long nano = System.nanoTime();

String userDir = System.getProperty("user.dir");
String path = System.getenv("PATH");

System.arraycopy(src, 0, dest, 0, length);

十三、枚举与正则

枚举

java 复制代码
enum Status {
    ACTIVE, INACTIVE
}

Status s = Status.valueOf("ACTIVE");
Status[] values = Status.values();

EnumSet<Status> set = EnumSet.of(Status.ACTIVE);
EnumMap<Status, String> map = new EnumMap<>(Status.class);

正则

java 复制代码
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("abc123");

if (matcher.find()) {
    System.out.println(matcher.group()); // 123
}

boolean matches = "13800138000".matches("1[3-9]\\d{9}");

十四、常用 API 速查表

场景 推荐 API
字符串判空 StringUtils.isBlank / str.isBlank()
字符串拼接 String.join / StringJoiner / Collectors.joining
集合创建 List.of / Map.of / Set.of
条件删除 removeIf
Map 累加 merge / computeIfAbsent
集合转流 stream()
分组 Collectors.groupingBy
判空 Optional.ofNullable
日期时间 LocalDate / LocalDateTime
格式化日期 DateTimeFormatter
文件读写 Files.readString / Files.writeString
JSON Jackson / Gson
线程池 ExecutorService
异步 CompletableFuture
并发计数 LongAdder / AtomicInteger
精确计算 BigDecimal
随机数 ThreadLocalRandom
唯一 ID UUID.randomUUID()

十五、总结

Java 日常开发常用的 API 并不需要全部记住,但以下几类建议熟练掌握:

  1. 字符串 :String、StringBuilder、StringJoiner、String.format。
  2. 集合 :List、Map、Set、Collections、Arrays。
  3. Stream :filter、map、collect、groupingBy、joining。
  4. Optional :ofNullable、map、orElseGet、ifPresent。
  5. 日期时间 :LocalDate、LocalDateTime、DateTimeFormatter、Duration、Period。
  6. 文件 IO :Path、Files、try-with-resources。
  7. 并发 :ExecutorService、CompletableFuture、ConcurrentHashMap、LongAdder。
  8. 工具类 :Objects、StringUtils、CollectionUtils。
  9. JSON:Jackson / Gson。
  10. 数学 :BigDecimal、ThreadLocalRandom、UUID。

真正提升开发效率的关键,不是背 API,而是知道 什么场景该用什么 API,并优先选择更安全、更简洁、更现代的写法。

相关推荐
小鹿的周先生1 小时前
第16章-RAG
java·人工智能·ai编程
夜不会漫长1 小时前
C++:内存管理
java·开发语言·c++
vipxieliang2 小时前
ValidX 财务系统发票验证:发票号、税号、金额校验
java·spring boot
天空鸟_时光不老2 小时前
06-给AI流程加一道人工闸门
java·人工智能·spring boot·后端·spring·spring cloud·架构
夜之眷属2 小时前
JVM实战:服务器堆外内存去哪了(NMT实测)
java·服务器·jvm·后端·性能优化
fundoit2 小时前
OIDC的UserInfo端点
java·架构·oauth2·oidc
Wang's Blog2 小时前
Java框架 SpringCloud 快速入门: Nacos 配置管理之添加配置与 dataId 命名规范
java·开发语言·spring cloud
JAVA面经实录9172 小时前
Java高级后端 · 全套面试通关手册(Nginx)
java·nginx·面试
阿俊-全栈开发2 小时前
LikeShop单商户Java商城如何从容承接高并发流量?
java·开发语言·spring boot·spring·系统架构