java
它能做什么
这份指南教你如何编写更高效、更现代的 Java 代码。它通过示例展示如何使用较新的语言特性,让代码更简洁、更易读。
适用场景
- ✓当你想学习编写 Java 代码的新方法时。
- ✓当你需要审查或改进现有的 Java 代码时。
- ✓当你想使用现代 Java 特性时。
技能链接
https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/super-code/java/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“如何使用 Streams 对 Java 列表中的元素进行过滤和转换?”
每周 5 个新技能,1 分钟读完。
工作原理
AI 会将你的代码与 Java 最佳实践示例进行对比。它会建议使用 Streams、Optional 和 Records 等特性来简化常见任务,并避免出错。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Java: Idiomatic Efficiency Reference
When to Use
- Use this skill when the task matches this description: Language-specific super-code guidelines for java.
Table of Contents
- Streams & Collections
- Optional
- Records & Data Classes
- Switch Expressions
- Concurrency
- Error Handling
- Anti-patterns specific to Java
1. Streams & Collections {#streams}
// ❌ Imperative accumulation
List<String> result = new ArrayList<>();
for (Item item : items) {
if (item.isActive()) result.add(item.getName().toUpperCase());
}
// ✅
List<String> result = items.stream()
.filter(Item::isActive)
.map(item -> item.getName().toUpperCase())
.toList(); // Java 16+; use .collect(Collectors.toList()) before
// ❌ Manual grouping
Map<String, List<Item>> grouped = new HashMap<>();
for (Item item : items) {
grouped.computeIfAbsent(item.getCategory(), k -> new ArrayList<>()).add(item);
}
// ✅
Map<String, List<Item>> grouped = items.stream()
.collect(Collectors.groupingBy(Item::getCategory));
// ❌ Manual sum
int total = 0;
for (Order o : orders) total += o.getAmount();
// ✅
int total = orders.stream().mapToInt(Order::getAmount).sum();
Prefer method references (Item::isActive) over equivalent lambdas (item -> item.isActive()).
2. Optional {#optional}
// ❌ Null check chain
String city = null;
if (user != null && user.getAddress() != null) {
city = user.getAddress().getCity();
}
// ✅
String city = Optional.ofNullable(user)
.map(User::getAddress)
.map(Address::getCity)
.orElse(null);
// ❌ Optional.get() without isPresent()
String name = optional.get(); // throws if empty
// ✅
String name = optional.orElse("default");
// or: optional.orElseThrow(() -> new IllegalStateException("name required"));
// ❌ Optional as a field or parameter (anti-pattern)
class User { private Optional<String> nickname; }
// ✅ — Optional is for return types only
class User { private String nickname; } // nullable field
public Optional<String> getNickname() { return Optional.ofNullable(nickname); }
3. Records & Data Classes {#records}
// ❌ Manual POJO
class Point {
private final int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return x; }
public int getY() { return y; }
// + equals, hashCode, toString...
}
// ✅ (Java 16+)
record Point(int x, int y) {}
// ❌ Builder pattern for a 2-field object
User user = new User.Builder().name("Alice").age(30).build();
// ✅ — use record or constructor directly for small objects
record User(String name, int age) {}
var user = new User("Alice", 30);
Use record for any immutable data carrier. Keep builders only for objects with many optional fields.
4. Switch Expressions {#switch}
// ❌ Switch statement with fall-through and break
String label;
switch (status) {
case ACTIVE: label = "Active"; break;
case INACTIVE: label = "Inactive"; break;
default: label = "Unknown";
}
// ✅ (Java 14+)
String label = switch (status) {
case ACTIVE -> "Active";
case INACTIVE -> "Inactive";
default -> "Unknown";
};
// ❌ instanceof + cast
if (shape instanceof Circle) {
Circle c = (Circle) shape;
return c.radius() * c.radius() * Math.PI;
}
// ✅ Pattern matching (Java 16+)
if (shape instanceof Circle c) {
return c.radius() * c.radius() * Math.PI;
}
5. Concurrency {#concurrency}
// ❌ Raw Thread creation
Thread t = new Thread(() -> doWork());
t.start();
// ✅
ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor(); // Java 21
exec.submit(() -> doWork());
// ❌ synchronized on this for fine-grained state
synchronized(this) { counter++; }
// ✅
AtomicInteger counter = new AtomicInteger();
counter.incrementAndGet();
Prefer CompletableFuture.allOf() over blocking .get() chains for parallel async work.
6. Error Handling {#errors}
// ❌ Catching Exception to log and swallow
try {
risky();
} catch (Exception e) {
log.error("error", e);
}
// ✅ — rethrow as unchecked if you can't handle it
try {
risky();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
// ❌ Checked exceptions declared on every method
…
常见问题
Java 中的“Records”是什么?
Records 是一种简单的方式,用来创建保存数据的不可变类。它就像一个“信息容器”,不需要编写大量重复的代码。
为什么要使用“Optional”?
Optional 用于处理可能存在也可能不存在的值(避免 null 错误)。这样代码更安全,也能更清楚地表明可能会得到什么结果。
什么是“Streams”?
Streams 是一种以更声明式、更高效的方式处理数据序列(如列表)的方法。你可以把过滤、转换等操作串联起来。
详情
热度
- GitHub 星标
- 48k
- 排名
- #5893
- 许可证
- MIT
- 更新时间
- 2026/10/15
评论
- …
同一仓库的更多技能
00-andruia-consultant
48k帮你的智能体启动或改进 AI 项目。它可以分析代码、推荐工具,并用西班牙语制定行动计划。
007
48k让你的智能体执行安全审计和威胁建模。它有助于保护项目免受攻击和漏洞的威胁。
10-andruia-skill-smith
48k帮你的智能体创建或改进 AI 工具。它可以定义工具的工作方式、编写文档,并验证其结构。
20-andruia-niche-intelligence
48k让你的智能体创建某个特定行业的摘要。它有助于借助可靠的信息来源,了解项目的背景、规则、使用模式和风险。