You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 default Map (immutable hash map) throughout—no mutable state is involved.
  • Efficient Lookups: Converting listb to 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 of lista and m is the size of listb.
  • Safe Transformation: Using flatMap with Option ensures we only include ObjC instances where a matching b_type exists in listb—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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:33:46