Java Stream API 实战:对象列表属性提取与去重
在实际业务开发中,我们经常需要从实体对象集合中提取特定字段,并去除重复值。使用 Java 8 引入的 Stream API 可以让这段逻辑变得简洁且易读。
List<AlarmTimeTrend> list = homePageMapper.alarmTimeTrend(cp);
List<Integer> alarmTypeLis = list.stream()
.map(AlarmTimeTrend::getAlarmType)
.collect(Collectors.toList())
.stream()
.distinct()
.collect(Collectors.toList());
上面的写法虽然能跑通,但中间多了一次 collect 和 stream 的切换。如果数据量较大,会产生额外的内存开销。作为资深开发,我们通常建议直接链式调用,减少中间状态。
List<Integer> alarmTypeLis = list.stream()
.map(AlarmTimeTrend::getAlarmType)
.distinct()
.collect(Collectors.toList());
这样不仅代码更短,执行效率也更高。Stream 管道的设计初衷就是支持这种惰性求值和链式处理,善用它能显著提升代码的可维护性。


