你熟悉Java 8的哪些特性?请举例说明
Java 8引入了许多新的特性和功能,以下是其中一些主要特性及其示例:
- 函数式编程:新增了Lambda表达式和Stream API。例如,我们可以使用Stream API对一组数进行排序:
List<Integer> numbers = Arrays.asList(3, 2, 1);
numbers.sort(Comparator.reverseOrder()); //降序排序
- 垂直扩展性:引入了Optional类来避免NullPointerException。示例:
String maybeValue = "This might not be null!";
Optional<String> optionalValue = Optional.ofNullable(maybeValue);
if (optionalValue.isPresent()) { // 如果值存在
System.out.println(optionalValue.get()); // 打印值
} else { // 如果值不存在,不会执行这里
System.out.println("Value is missing!"); // 输出提示信息
}
- Date/Time API:引入了LocalDate、LocalTime、LocalDateTime等类来处理日期和时间。示例:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class DateTimeExample {
public static void main(String[] args) {
// 创建当前日期时间
LocalDateTime now = LocalDateTime.now();
// 设置日期时间格式
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
// 将当前日期时间转换为字符串
String formattedDateTime = now.format(formatter);
System.out.println("Current Date and Time: " + formattedDateTime);
}
}
这就是Java 8的一些主要特性及其示例。
还没有评论,来说两句吧...