I have two list of same model class (STUDENT), sample student object structure is given below,
{ "_id": "5a66d78690429a1d897a91ed", "division": "G", "standard": "X", "section": "Secondary", "lastName": "Sawant", "middleName": "Sandeep", "firstName": "Shraddha", "pin": 12345, "isEditable": true, "isTracked": false }
One list have 3 objects and other 2. lets say, List A has 1, 2, 3 students and List B has 1, 2
So my question is there any inbuilt functions to get the uncommon element by comparing just the id? If not how can i solve this issue.
FYI, following are the two approaches i have made to solve, but failed miserably.
Approach 1.
internal fun getDistinctStudents(studentsList: List<Students>, prefStudents: List<Students>): List<Students> { val consolidated = prefStudents.filter { prefStudents.any { students: Students -> it._id == students._id } } return prefStudents.minus(consolidated) }
Approach 2.
internal fun getDistinctStudents(studentsList: List<Students>, prefStudents: List<Students>): List<Students> { val consolidatedStudents = studentsList + prefStudents val distinctStudents = consolidatedStudents.distinctBy{ it._id } return prefStudents.minus(distinctStudents) }
Any kind of help will be greatly appreciated.
Thanks
For retrieving an element at a specific position, there is the function elementAt() . Call it with the integer number as an argument, and you'll receive the collection element at the given position. The first element has the position 0 , and the last one is (size - 1) .
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With