Scala非可变集合实现:基于另一个列表过滤并构造对象列表
Yes, this is absolutely achievable in Scala with immutable collections!
Scala’s focus on immutability makes this task straightforward and efficient. Here’s a step-by-step implementation using idiomatic, non-variable collections:
Step 1: Define Immutable Data Models
First, let’s define case classes to represent the elements in your lists and the target ObjC type. Case classes are immutable by default and work perfectly for this use case:
// Represents elements in lista case class ElementA(a_type: String) // Represents elements in listb case class ElementB(b_type: String, b_name: String) // The target object we want to construct case class ObjC(aType: String, bName: String)
Step 2: Implement the Transformation Function
We’ll use Scala’s immutable List and Map (the default Map in Scala is immutable) to efficiently process the lists:
def buildObjCList(lista: List[ElementA], listb: List[ElementB]): List[ObjC] = { // Convert listb into an immutable map for O(1) lookups (key: b_type, value: b_name) val typeToNameMap: Map[String, String] = listb.map(b => b.b_type -> b.b_name).toMap // Iterate over lista, filter matches, and construct ObjC instances lista.flatMap { elementA => // Use get() to safely look up the a_type in the map (returns Option[String]) typeToNameMap.get(elementA.a_type).map(bName => ObjC(elementA.a_type, bName)) } }
How This Works
- Immutable Collections: We use
List(immutable sequence) and the defaultMap(immutable hash map) throughout—no mutable state is involved. - Efficient Lookups: Converting
listbto a map reduces the lookup time from O(n) per element to O(1), making the overall operation O(n + m) where n is the size oflistaand m is the size oflistb. - Safe Transformation: Using
flatMapwithOptionensures we only includeObjCinstances where a matchingb_typeexists inlistb—no nulls or runtime errors from missing keys.
Example Usage
Let’s test this with sample data:
val lista = List(ElementA("type1"), ElementA("type2"), ElementA("type3")) val listb = List(ElementB("type1", "Name1"), ElementB("type3", "Name3")) val result = buildObjCList(lista, listb) // Result: List(ObjC(type1,Name1), ObjC(type3,Name3))
This implementation is clean, efficient, and aligns perfectly with Scala’s functional programming principles using immutable collections.
内容的提问来源于stack exchange,提问作者Larry
相关产品推荐
相关产品推荐

