Get uncommon elements from two list - KOTLIN

A more Kotlin way to achieve what Ahmed Hegazy posted. The map will contain a list of elements, rather than a key and count.

Using HashMap and Kotlin built-ins. groupBy creates a Map with a key as defined in the Lambda (id in this case), and a List of the items (List for this scenario)

Then filtering out entries that have a list size other than 1.

And finally, converting it to a single List of Students (hence the flatMap call)

val list1 = listOf(Student("1", "name1"), Student("2", "name2"))
val list2 = listOf(Student("1", "name1"), Student("2", "name2"), Student("3", "name2"))

val sum = list1 + list2
return sum.groupBy { it.id }
    .filter { it.value.size == 1 }
    .flatMap { it.value }

I know that this is an old post but I believe there is a neater and shorter solution. See sample below using Mikezx6r's data whose answer was accepted above.

val list1 = listOf(Student("1", "name1"), Student("2", "name2"))
val list2 = listOf(Student("1", "name1"), Student("2", "name2"), Student("3", "name2"))

val difference = list2.toSet().minus(list1.toSet())