在Java的世界里,Java 8无疑是一个重要的里程碑,它引入了一系列的核心新特性,这些特性不仅简化了代码的编写,也提高了程序的执行效率。以下是一些Java 8的核心新特性,以及如何通过实用案例来帮助你轻松入门。

1. Lambda表达式与Stream API

Lambda表达式

Lambda表达式允许你以更简洁的方式表示一个匿名函数。这在处理集合操作和事件处理时尤其有用。

案例:假设我们有一个学生类,我们需要根据学生的成绩排序。

import java.util.Arrays;
import java.util.List;

class Student {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }
}

public class LambdaExample {
    public static void main(String[] args) {
        List<Student> students = Arrays.asList(
            new Student("Alice", 85),
            new Student("Bob", 92),
            new Student("Charlie", 78)
        );

        students.sort((s1, s2) -> s1.getScore() - s2.getScore());

        for (Student student : students) {
            System.out.println(student.getName() + ": " + student.getScore());
        }
    }
}

Stream API

Stream API提供了处理集合的高阶函数,如filter、map、reduce等,使得集合操作更加直观。

案例:计算所有学生的平均分。

int averageScore = students.stream()
                            .mapToInt(Student::getScore)
                            .average()
                            .orElse(0);
System.out.println("Average Score: " + averageScore);

2. 方法引用

方法引用允许你直接引用另一个对象的方法来创建Lambda表达式。

案例:使用方法引用来打印学生名字。

students.forEach(Student::getName);

3. 默认方法

默认方法允许接口添加具体实现的方法,这避免了实现类需要覆盖这些方法。

案例:在Comparable接口中添加一个默认方法compareByScore。

public interface ComparableStudent extends Comparable<Student> {
    default int compareByScore(Student other) {
        return Integer.compare(this.getScore(), other.getScore());
    }
}

public class Student implements ComparableStudent {
    // Student class implementation
}

4. 新的日期时间API

Java 8引入了新的日期时间API,如LocalDate、LocalTime和LocalDateTime等,这些类使得日期时间的处理更加直观。

案例:获取当前日期和时间。

LocalDateTime now = LocalDateTime.now();
System.out.println("Current Date and Time: " + now);

5. Optional类

Optional类用于避免返回null值,这是Java中常见的错误来源。

案例:使用Optional来安全地处理可能为null的对象。

Optional<Student> optionalStudent = Optional.ofNullable(findStudentById(1));
optionalStudent.ifPresent(student -> System.out.println(student.getName()));

通过上述案例,你可以看到Java 8的新特性如何简化代码和提高效率。这些特性不仅让你能够以更现代的方式编写Java代码,而且还能让你在处理复杂问题时更加得心应手。不断实践这些新特性,你将更快地掌握它们,并在未来的Java项目中发挥它们的威力。