来自:程序通事
Text Blocks 终定板
Records (Second Preview)
public record Point(int x,int y) {
}
List<Merchant> findTopMerchants(List<Merchant> merchants, int month) {
// Local record
record MerchantSales(Merchant merchant, double sales) {}
return merchants.stream()
.map(merchant -> new MerchantSales(merchant, computeSales(merchant, month)))
.sorted((m1, m2) -> Double.compare(m2.sales(), m1.sales()))
.map(MerchantSales::merchant)
.collect(toList());
}
// local enums
public void organisePeople(List<Person> people) {
enum Role {
Employee, Customer, Both, None
}
HashMap<Role, List<Person>> peopleByRole = new HashMap<>();
people.stream()
.filter(Person::isCustomer)
.forEach(person -> peopleByRole.computeIfAbsent(Role.Customer, role -> new ArrayList<>())
.add(person));
// 其他业务逻辑
}
// local interface
public void localInterface() {
interface MyInterface {
void doSomething();
}
MyInterface testInterface = new MyInterface() {
@Override
public void doSomething() {
System.out.println("Hello World!");
}
};
// 其他业务逻辑
}
Pattern Matching for instanceof (Second Preview)
if (obj instanceof String) {
String str = (String) obj;
// use str
}
if (obj instanceof String s) {
s.contains("T");
} else {
// 编译错误
//s.contains("T");
}
Sealed Classes (Preview)
public final class String
interface DefaultExample {
}
public sealed class Shape
permits Circle, Rectangle, Square {...}
Shape
类只能被 Circle
,Rectangle
,Square
继承,再也不能被其他类继承。public final class Circle extends Shape {...}
public sealed class Rectangle extends Shape
permits TransparentRectangle, FilledRectangle {...}
public final class TransparentRectangle extends Rectangle {...}
public sealed interface Expr
permits ConstantExpr, PlusExpr, TimesExpr, NegExpr {...}
public record ConstantExpr(int i) implements Expr {...}
public record PlusExpr(Expr a, Expr b) implements Expr {...}
public record TimesExpr(Expr a, Expr b) implements Expr {...}
public record NegExpr(Expr e) implements Expr {...}
ZGC
-XX:+UseZGC command-line