Lambda 对集合的常用表达式
集合操作
平均值、最大值、最小值、求合
准备步骤
@Getter
@Setter
@Accessors(chain = true)
@TableName(value = "sys_user", autoResultMap = true)
@Schema(name = "UserEntity对象", description = "用户表")
public class UserEntity extends BaseEntity {
@Schema(description = "用户id")
@TableId(value = "user_id", type = IdType.ASSIGN_ID)
private Long userId;
@Schema(description = "用户名")
@TableField("user_name")
private String userName;
@Schema(description = "年龄")
@TableField("age")
private Integer age;
@Schema(description = "备注")
@TableField("remark")
private String remark;
}
List<UserEntity> userEntityList = userMapper.selectList(new Page<>(1, 100), new LambdaQueryWrapper<>());
// 按int类型统计,同样有类型 summarizingLong、summarizingDouble 方法 进行统计。
IntSummaryStatistics summaryStatistics = userEntityList.stream().collect(Collectors.summarizingInt(UserEntity::getAge));
log.info("年龄平均值:{}", summaryStatistics.getAverage()); // 年龄平均值:
log.info("人数:{}", summaryStatistics.getCount()); // 人数:
log.info("年龄最大值:{}", summaryStatistics.getMax()); // 年龄最大值:
log.info("年龄最小值:{}", summaryStatistics.getMin()); // 年龄最小值:
log.info("年龄总和:{}", summaryStatistics.getSum()); // 年龄总和:
获取某列的值,并且去重
List<UserEntity> userEntityList = userMapper.selectList(new Page<>(1, 100), new LambdaQueryWrapper<>());
List<String> userNameList = userEntityList.stream().distinct().map(UserEntity::getUserName).toList();
以某列分组
List<UserEntity> userEntityList = userMapper.selectList(new Page<>(1, 100), new LambdaQueryWrapper<>());
//以某列分组
Map<Long, List<UserEntity>> collect = userEntityList.stream().collect(Collectors.groupingBy(UserEntity::getUserId));
//list转map
Map<Long, UserEntity> entityMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getUserId, a -> a, (k1, k2) -> k1));
过滤年龄小于18岁,大于2岁的用户信息
List<UserEntity> userEntityList = userMapper.selectList(new Page<>(1, 100), new LambdaQueryWrapper<>());
List<UserEntity> list = userEntityList.stream().filter(d -> d.getAge() < 18 && d.getAge() > 2).toList();
parallelStream() 和 stream()的比较
选择使用.parallelStream()还是.stream()取决于具体的需求和场景。如果需要并行处理大量数据或者处理操作耗时较长,可以考虑使用.parallelStream()以提高性能。如果操作简单、数据量较小或者对处理顺序有严格要求,可以使用.stream()。在使用并行流时,需要注意线程安全性和对操作顺序的理解。