Java 计算 List 列表中所有 binds 的总数示例
以下是一个使用 Java 语言的示例代码,演示了如何计算列表 models 中所有 binds 的总数:
import java.util.ArrayList;
import java.util.List;
class Model {
private String sn;
private List<String> binds;
public Model(String sn, List<String> binds) {
this.sn = sn;
this.binds = binds;
}
public List<String> getBinds() {
return binds;
}
}
public class Main {
public static void main(String[] args) {
List<Model> models = new ArrayList<>();
// 添加示例数据
models.add(new Model('SN1', List.of('bind1', 'bind2')));
models.add(new Model('SN2', List.of('bind3', 'bind4', 'bind5')));
models.add(new Model('SN3', List.of('bind6')));
int totalBinds = 0;
for (Model model : models) {
totalBinds += model.getBinds().size();
}
System.out.println('总共有 ' + totalBinds + ' 个binds。');
}
}
上述代码中,我们定义了一个 Model 类,该类具有属性 sn 和 binds,其中 sn 表示模型的序列号,binds 表示与该模型相关的绑定列表。
在主函数中,我们创建了一个 List 列表 models,并添加了一些示例数据。然后,我们使用 for 循环遍历列表 models,获取每个 Model 对象的 binds 列表的大小,并将其累加到 totalBinds 变量中。最后,我们打印出 totalBinds 的值,即所有 binds 的总数。
运行上述代码,输出结果为:
总共有 6 个binds。
这表示列表 models 中共有 6 个 binds。
原文地址: https://www.cveoy.top/t/topic/pcqh 著作权归作者所有。请勿转载和采集!