Pharo技术问询:如何从嵌套OrderedCollection提取元素生成单层集合?
解决Pharo嵌套OrderedCollection转单层的问题
你可以用以下两种简洁的方式实现需求:
方法一:使用flatCollect:方法
flatCollect:会自动遍历原集合中的每个子集合,并将子集合的元素平铺到结果集合中:
flattenedCollection := originalCollection flatCollect: [:subCollection | subCollection].
如果需要确保结果严格是OrderedCollection类型(部分场景下flatCollect:可能返回其他Collection子类),可以加上类型转换:
flattenedCollection := (originalCollection flatCollect: [:subCollection | subCollection]) asOrderedCollection.
方法二:使用inject:into:手动合并
通过初始化空集合,逐个添加子集合的所有元素:
flattenedCollection := originalCollection inject: OrderedCollection new into: [:result :subCollection | result addAll: subCollection; yourself].
两种方法都能将包含三个子OrderedCollection的外层集合,转换为包含所有String、String、Date元素的单层OrderedCollection,且保留原元素的顺序。
内容的提问来源于stack exchange,提问作者Mansour Faouziel
相关产品推荐
相关产品推荐

