在Java 8中,Stream API提供了一种高效且易于使用的方式来处理集合数据。使用流(Stream)的组合规范列表,通常指的是通过流的中间操作(如filter、map)和终端操作(如collect)来对数据进行一系列的处理和转换。
流(Stream):是Java 8引入的一个新的抽象层,用于处理集合类库的弊端,提供了更高效的数据处理方式。
中间操作:返回一个新的流,允许链式调用。常见的中间操作有filter、map、flatMap、distinct、sorted等。
终端操作:触发流的处理并产生结果或副作用,如collect、forEach、reduce、min、max等。
类型:
应用场景:
假设我们有一个Person
类和一个包含多个Person
对象的列表,我们想要筛选出年龄大于18岁的人,并将他们的名字转换为大写,最后收集到一个新的列表中。
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public class StreamExample {
public static void main(String[] args) {
List<Person> people = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 17),
new Person("Charlie", 30)
);
List<String> adultsInUpperCase = people.stream()
.filter(person -> person.getAge() > 18) // 过滤出成年人
.map(person -> person.getName().toUpperCase()) // 名字转大写
.collect(Collectors.toList()); // 收集结果到列表
System.out.println(adultsInUpperCase); // 输出: [ALICE, CHARLIE]
}
}
问题:流操作中出现空指针异常(NullPointerException)。
原因:可能是流中的某个元素为null,或者在处理过程中引用了null对象。
解决方法:
Optional
类来安全地处理可能为null的值。filter(Objects::nonNull)
来排除null元素。List<String> safeNames = people.stream()
.filter(person -> person != null) // 排除null元素
.map(Person::getName)
.filter(Objects::nonNull) // 确保名字不为null
.collect(Collectors.toList());
通过以上方法,可以有效地避免在流操作中出现空指针异常。
领取专属 10元无门槛券
手把手带您无忧上云