代码之家  ›  专栏  ›  技术社区  ›  ant2009

基于另一个列表从列表中删除和添加Int

  •  0
  • ant2009  · 技术社区  · 5 年前
    Kotlin 1.4.72
    

    我有一个名为Int的列表 listOfSelectedIds

    将生成另一个名为的列表 currentIds .

    我希望能够添加或删除 所选ID列表 基于以下条件:

    如果有来自的ID 当前ID 存在于 所选ID列表 则应从中删除该ID 所选ID列表 否则,如果ID不存在,则应将其添加到 listOfSelectedids .

    名单上有这样做的操作员吗。

    例子

    listOfSelectedIds [1, 2, 3, 4, 5]
    listOfCurrentIds [4, 5, 6, 7]
    

    因此,listOfSelectedDs的最终结果将是 [1, 2, 3, 6, 7] 4和5已被删除。添加了6和7。

    提前感谢,

    0 回复  |  直到 5 年前
        1
  •  3
  •   Алексей Лумпов    5 年前

    您也可以在一次迭代中完成此操作

    fun main() {
        val selectedIds = setOf(1, 2, 3, 4, 5) // Set A
        val currentIds = setOf(4, 5, 6, 7) // Set B
    
        println(selectedIds.xor(currentIds))
    }
    
    
    fun <T> Set<T>.xor(b: Set<T>): Set<T> {
        val mutableB = b.toMutableSet()
        return filterNot { mutableB.remove(it) } union mutableB
    }
    
        2
  •  3
  •   Siddharth Kamaria    5 年前

    您可以将列表更改为 Set 并执行设定操作。从数学的角度来看,它将 (A-B) U (B-A) .

    1. 从A中减去B,从B中减去A。

    2. 将步骤1生成的两个集合进行并集。

      fun main() {
          val selectedIds = setOf(1, 2, 3, 4, 5) // Set A
          val currentIds = setOf(4, 5, 6, 7) // Set B
          val selectedIdsNotInCurrentIds = selectedIds subtract currentIds // Set A-B
          val currentIdsNotInSelectedIds = currentIds subtract selectedIds // Set B-A
          val result = selectedIdsNotInCurrentIds union currentIdsNotInSelectedIds // (A-B) U (B-A)
          println(result)
      }
      
    推荐文章