Sobes.tech
Middle

How would you implement a project that needs to gather different elements into one list, while excluding duplicates of the same elements?

sobes.tech AI

Answer from AI

// Create a MutableList to store elements
val combinedList = mutableListOf<Any>()

// Create a Set to track unique elements and prevent duplicates
val uniqueElements = mutableSetOf<Any>()

// Add elements from various sources (list examples)
val list1 = listOf("Element 1", 123, true, "Element 1")
val list2 = listOf(456, "Element 2", false, 123)

// Iterate over each list and add elements if they are unique
list1.forEach { element ->
    if (uniqueElements.add(element)) { // Set.add() returns true if the element was successfully added (i.e., it is unique)
        combinedList.add(element)
    }
}

list2.forEach { element ->
    if (uniqueElements.add(element)) {
        combinedList.add(element)
    }
}

// combinedList now contains unique elements from list1 and list2
// uniqueElements contains the same unique elements in an unordered form

// Example usage of combinedList
combinedList.forEach { element ->
    println(element)
}