Lambda表达式使用方法
- 基本语法
Lambda表达式的基本形式为(参数) -> 表达式
或(参数) -> { 语句; }
// 无参数,返回值为String
() -> "Hello Lambda"
// 一个参数,不返回值
x -> System.out.println(x)
// 两个参数,返回值为int
(a, b) -> a + b
- 使用场景
常用于简化函数式接口的实现,如Runnable、Comparator等
// 使用前
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("传统写法");
}
}).start();
// 使用后
new Thread(() -> System.out.println("Lambda写法")).start();
- 变量捕获
Lambda表达式可以捕获外部的final或effectively final变量
final int num = 1;
Consumer<Integer> consumer = (value) -> System.out.println(value + num);
consumer.accept(2); // 输出3
Stream API使用方法
- 创建Stream
通过集合、数组等创建Stream
// 集合创建
List<String> list = Arrays.asList("a", "b", "c");
Stream<String> stream = list.stream();
// 数组创建
String[] array = {
"a", "b", "c"};
Stream<String> stream = Arrays.stream(array);
// 直接创建
Stream<String> stream = Stream.of("a", "b", "c");
- 中间操作
对Stream进行转换、过滤等操作
// 过滤
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);
stream.filter(x -> x % 2 == 0).forEach(System.out::println); // 输出2,4
// 映射
Stream<String> stream = Stream.of("a", "b", "c");
stream.map(String::toUpperCase).forEach(System.out::println); // 输出A,B,C
- 终端操作
触发Stream的执行并产生结果
// 收集
List<String> list = Stream.of("a", "b", "c").collect(Collectors.toList());
// 计数
long count = Stream.of(1, 2, 3).count();
// 归约
int sum = Stream.of(1, 2, 3).reduce(0, (a, b) -> a + b);
接口默认方法与静态方法封装
- 默认方法封装
在接口中定义默认方法,提供通用实现
public interface MyInterface {
default void defaultMethod() {
System.out.println("默认方法实现");
}
}
- 静态方法封装
在接口中定义静态方法,提供工具类功能
public interface MyInterface {
static void staticMethod() {
System.out.println("静态方法实现");
}
}
- 使用示例
public class MyClass implements MyInterface {
// 无需实现默认方法
}
// 调用默认方法
MyClass obj = new MyClass();
obj.defaultMethod();
// 调用静态方法
MyInterface.staticMethod();
Optional类封装方法
- 创建Optional
// 创建非空值的Optional
Optional<String> optional = Optional.of("value");
// 创建可能为空的Optional
Optional<String> optional = Optional.ofNullable(null);
// 创建空的Optional
Optional<String> optional = Optional.empty();
- 安全获取值
// 获取值,不存在则返回默认值
String value = optional.orElse("default");
// 获取值,不存在则抛出异常
String value = optional.orElseThrow(() -> new IllegalArgumentException());
- 链式处理
optional.ifPresent(System.out::println);
optional.map(String::length).ifPresent(System.out::println);
日期时间API封装方法
- 日期时间工具类封装
public class DateUtils {
// 获取当前日期
public static LocalDate getCurrentDate() {
return LocalDate.now();
}
// 日期格式化
public static String formatDate(LocalDate date, String pattern) {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
return date.format(formatter);
}
// 计算日期差
public static long daysBetween(LocalDate start, LocalDate end) {
return ChronoUnit.DAYS.between(start, end);
}
}
- 使用示例
// 获取当前日期
LocalDate now = DateUtils.getCurrentDate();
// 格式化日期
String formattedDate = DateUtils.formatDate(now, "yyyy-MM-dd");
// 计算日期差
LocalDate start = LocalDate.of(2023, 1, 1);
LocalDate end = LocalDate.of(2023, 12, 31);
long days = DateUtils.daysBetween(start, end);
方法引用封装方法
- 静态方法引用
public class MathUtils {
public static int square(int num) {
return num * num;
}
}
// 使用方法引用
Function<Integer, Integer> square = MathUtils::square;
int result = square.apply(5); // 结果为25
- 实例方法引用
public class StringUtils {
public boolean isEmpty(String str) {
return str == null || str.isEmpty();
}
}
// 使用方法引用
StringUtils utils = new StringUtils();
Predicate<String> isEmpty = utils::isEmpty;
boolean result = isEmpty.test(""); // 结果为true
Nashorn JavaScript引擎封装
- JavaScript执行工具类
public class JsExecutor {
private ScriptEngine engine;
public JsExecutor() {
ScriptEngineManager manager = new ScriptEngineManager();
engine = manager.getEngineByName("nashorn");
}
// 执行JavaScript代码
public Object execute(String script) throws ScriptException {
return engine.eval(script);
}
// 调用JavaScript函数
public Object invokeFunction(String functionName, Object... args)
throws ScriptException, NoSuchMethodException {
return ((Invocable) engine).invokeFunction(functionName, args);
}
}
- 使用示例
JsExecutor executor = new JsExecutor();
// 执行脚本
executor.execute("function add(a, b) { return a + b; }");
// 调用函数
Object result = executor.invokeFunction("add", 3, 5);
类型注解封装
- 自定义类型注解
@Target({
ElementType.TYPE_USE, ElementType.TYPE_PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNull {
String message() default "不能为空";
}
- 在泛型中使用
public class Container<@NotNull T> {
private T value;
public Container(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
以上是JDK 1.8新特性的使用方法及组件封装示例。通过合理使用这些特性,可以显著提高Java代码的简洁性、可读性和可维护性。
JDK1.8, 新特性,lambda 表达式,Stream API, 方法引用,默认方法,Optional 类,CompletableFuture, 新日期时间 API, Nashorn 引擎,PermGen 移除,并行数组排序,JavaScript 引擎,接口默认方法,Java 8 特性
准备了一些面试资料,需要的拿走
https://pan.quark.cn/s/4459235fee85