所有数据都基于UserInfo类,其中包含了 userId、userName、course、score 等字段,下面是如何使用Options、 Stream 、Function来处理 UserInfo 对象列表的一些示例
List<UserInfo> userInfoList = Arrays.asList(
new UserInfo(1L, "Alice", "Math", 90),
new UserInfo(2L, "Bob", "Physics", 85),
new UserInfo(3L, "Charlie", "Chemistry", 88),
new UserInfo(4L, "Diana", "Math", 92),
new UserInfo(5L, "Eve", "Physics", 89)
);
@Data
public static class UserInfo {
private Long userId;
private String userName;
private String course;
private int score;
public UserInfo(Long userId, String userName, String course, int score) {
this.userId = userId;
this.userName = userName;
this.course = course;
this.score = score;
}
public String getCourse() {
return course;
}
}
所有数据都基于UserInfo类,其中包含了 userId、userName、course、score 等字段,下面是如何使用 Java Stream API 来处理 UserInfo 对象列表的一些示例
List<UserInfo> userInfoList = List.of(
new UserInfo(1L, "Alice", "Math", 90),
new UserInfo(2L, "Bob", "Physics", 85),
new UserInfo(3L, "Charlie", "Chemistry", 88),
new UserInfo(4L, "Diana", "Math", 92),
new UserInfo(5L, "Eve", "Physics", 89)
);
一、Stream用法
Stream是Java 8中引入的全新API,可以极大地方便我们对集合、数组等数据源进行连续操作
1.1 流的创建
通过集合 Collection.stream() 创建 Stream,一般开发中常用这种方式创建流
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> streamFromCollection = names.stream();
通过数组 Arrays.stream 创建 Stream
String[] names = {"Alice", "Bob", "Charlie"};
Stream<String> streamFromArray = Arrays.stream(names);
通过