gpt4 book ai didi

java - 迭代对象列表、获取属性的最佳方法

转载 作者:行者123 更新时间:2023-11-30 05:24:33 24 4
gpt4 key购买 nike

如果存在某些属性值,从现有对象列表创建新属性列表的最佳方法是什么?我应该将列表转换为 map 吗?但后来我希望列表属性成为 Map 键,但我不知道如何获取这些属性。

我是否应该迭代此列表,如果列表中的某个属性具有值,则将该属性添加到新列表中,或者是否有更快或更好的方法来实现我想要的目标?

我需要这个新列表来创建带有动态标题的表格。

List<CommissionSchedule> commissionSched = commissionScheduleRepository.findByCarrier(carrier);

List <String> hs= new ArrayList<>();
for (CommissionSchedule cs: commissionSched){
if (cs.getCategory()!=null){
hs.add("Category");
} else if (cs.getAutoNew()!null){
hs.add("Auto New");
}
//...etc

}

这不仅仅是为每个属性执行一堆 if/else if 情况?

最佳答案

为什么不在 CommissionSchedule 类中添加评估员?

String getHs(){
return category !=null ? "Category":
autoNew !=null ? "Auto New" :
"others" ;
}

然后在循环中,只需要调用getHs()方法

使用流就像这样。

List<CommissionSchedule> commissionSched = 
commissionScheduleRepository.findByCarrier(carrier);

List<String> hs = commisionSched.stream()
.map(cs -> cs.getHs())
.collect(Collectors.toList());

或者,你也可以这样做

List <String> hs= new ArrayList<>();
for (CommissionSchedule cs: commissionSched){
hs.add(cs.getHs());
}

关于java - 迭代对象列表、获取属性的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58924731/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com