如何遍历ArrayList中Thing类对象的title字段,按字符数更新计数?
解决思路与代码实现
嗨,这问题不难搞定!咱们一步步调整你的循环逻辑,实现根据title里'o'的数量更新count的需求:
首先明确核心需求:遍历ArrayList<Thing>中的每个对象,不再固定给count加1,而是统计当前Thing的title里字母'o'的个数,把这个数字加到count上。
步骤1:遍历ArrayList的方式
推荐用Java的增强for循环(foreach),比普通for循环更简洁易读;当然普通for循环也能实现,我两种都给你写出来。
步骤2:统计title中'o'的数量
这里要注意两个细节:
- 调用
getTitle()方法获取title(符合面向对象封装原则,虽然你的title是默认权限,但用get方法更规范) - 处理title为
null的情况,避免空指针异常
你可以直接在循环内处理统计逻辑,也可以把统计逻辑抽成工具方法让代码更整洁,我两种方式都演示下。
完整代码示例
方式一:直接在循环内统计'o'的数量
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Thing> things = new ArrayList<>(); // 模拟添加测试对象 Thing thing1 = new Thing(); thing1.setTitle("Hello World"); // 含1个'o' Thing thing2 = new Thing(); thing2.setTitle("Look at the moon"); // 含3个'o' Thing thing3 = new Thing(); thing3.setTitle(null); // 空title,避免空指针 things.add(thing1); things.add(thing2); things.add(thing3); int count = 0; // 增强for循环版本 for (Thing thing : things) { String title = thing.getTitle(); if (title != null) { int oCount = 0; // 遍历title的每个字符统计'o' for (char c : title.toCharArray()) { if (c == 'o') { oCount++; } } count += oCount; // 把统计的o数量加到count上 } // title为null时跳过,不修改count } System.out.println("最终count值:" + count); // 输出应为1+3=4 } } // 你的Thing类 class Thing { String title; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
方式二:提取统计方法,代码更整洁
如果需要多次统计字符数量,把统计逻辑抽成工具方法会更方便:
// 工具方法:统计字符串中指定字符的数量 private static int countChar(String str, char target) { if (str == null) { return 0; } int count = 0; for (char c : str.toCharArray()) { if (c == target) { count++; } } return count; }
然后在循环里直接调用:
for (Thing thing : things) { count += countChar(thing.getTitle(), 'o'); }
额外说明
- 如果需要忽略大小写统计(比如'O'和'o'都算),只需要把判断条件改成
Character.toLowerCase(c) == 'o'即可。 - 要是你用Java 8及以上版本,还可以用Stream API实现,代码更简洁:
int count = things.stream() .map(Thing::getTitle) .filter(title -> title != null) .mapToInt(title -> (int) title.chars().filter(c -> c == 'o').count()) .sum();
这个适合对Stream API熟悉的场景,可读性也不错。
内容的提问来源于stack exchange,提问作者Julia Dune
相关产品推荐
相关产品推荐

