以下是一些Java8中常用的语法:
Lambda表达式
Lambda表达式允许我们以更紧凑的方式编写代码,尤其是在需要实现函数式接口时。它基本上是一个匿名函数,可以在需要时传递和使用。
List<String> names = Arrays.asList("John", "Smith", "Samuel");
names.forEach(name -> System.out.println(name));
Stream API
Stream API是一种处理集合数据的新方法。它提供了一种简单而强大的方式来对数据进行筛选、排序、映射等操作。
List<Integer> numbers = Arrays.asList(3, 2, 5, 6, 4, 1);
numbers.stream()
.filter(n -> n % 2 == 0)
.sorted()
.forEach(System.out::println);
方法引用
方法引用是一种更简洁的Lambda表达式形式,可以将方法作为参数传递,从而避免重复编写相同的代码。
List<String> names = Arrays.asList("John", "Smith", "Samuel");
names.forEach(System.out::println);
默认方法
默认方法是接口中的一种新特性,它允许在不破坏现有代码的情况下向接口添加新方法。
public interface MyInterface {
default void myDefaultMethod() {
System.out.println("This is a default method.");
}
}
时间API
Java8引入了一套全新的时间API,它提供了一种更好的方式来处理日期和时间。
LocalDateTime now = LocalDateTime.now();
System.out.println(now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
这只是Java8中一些常用的语法,还有很多其他的新特性和语法需要我们去探索和学习。