遍历Document列表时如何获取特定type的最后一个元素
实现思路
单次遍历列表即可完成需求,时间复杂度为O(n)、空间复杂度为O(1):遍历过程中维护一个临时变量,缓存最近一次遇到的type为MIC的Document对象,当碰到type为OTHER的元素时,直接读取这个缓存变量即可。
代码示例
Java 版本
// 简化的Document类定义 class Document { private String type; // 其他属性、getter、setter省略 public String getType() { return type; } } // 核心处理逻辑 List<Document> docList = // 你的Document列表 Document lastMic = null; for (Document doc : docList) { if ("MIC".equals(doc.getType())) { lastMic = doc; } else if ("OTHER".equals(doc.getType())) { // 直接取当前OTHER之前最后一个MIC,注意判空避免前面没有MIC的场景 Document targetMic = lastMic; // 此处写你对targetMic的处理逻辑 } // 其他类型的文档按需处理 }
Python 版本
# 简化的Document类定义 class Document: def __init__(self, doc_type): self.type = doc_type # 核心处理逻辑 doc_list = [] # 你的Document列表 last_mic = None for doc in doc_list: if doc.type == "MIC": last_mic = doc elif doc.type == "OTHER": # 直接取last_mic即可,注意判空处理前面无MIC的场景 target_mic = last_mic # 此处写后续处理逻辑
注意事项
- 如果遍历到
OTHER类型元素时,前面还没有出现过MIC类型元素,缓存变量会为null/None,需要做判空处理避免空指针异常 - 如果需要存储
OTHER和对应MIC的配对关系,可以额外定义结果集合,每次遇到OTHER时把配对关系存入集合即可
内容的提问来源于stack exchange,提问作者marramatteo
相关产品推荐
相关产品推荐

