Comparing two lists in kotlin

We Are Going To Discuss About Comparing two lists in kotlin. So lets Start this Java Article.

Comparing two lists in kotlin

  1. Comparing two lists in kotlin

    Just fyi you can call list1 == list2 without any extra work, if your custom object is based off of a data class (which automatically overrides equals for you).

  2. Comparing two lists in kotlin

    Just fyi you can call list1 == list2 without any extra work, if your custom object is based off of a data class (which automatically overrides equals for you).

Solution 1

Just fyi you can call list1 == list2 without any extra work, if your custom object is based off of a data class (which automatically overrides equals for you).

Original Author Rene Ferrari Of This Content

Solution 2

If you don’t bother about order of elements in both lists, and your goal is to just check that two lists are of exactly same elements, without any others, you can consider two mutual containsAll calls like:

var list1 = mutableListOf<String>()
var list2 = mutableListOf<String>()

if(list1.containsAll(list2) && list2.containsAll(list1)) {
    //both lists are of the same elements
}

Original Author DruidKuma Of This Content

Solution 3

Java lists implement equals method and two lists are defined to be equal if they contain the same elements in the same order. I guess, you are missing equals method in your MyObject class.

Original Author Dakshinamurthy Karra Of This Content

Solution 4

Using zip

zip returns a list of pairs built from the elements of this array and the other array with the same index. The returned list has length of the shortest collection.

fun listsEqual(list1: List<Any>, list2: List<Any>): Boolean {

    if (list1.size != list2.size)
        return false

    val pairList = list1.zip(list2)

    return pairList.all { (elt1, elt2) ->
        elt1 == elt2       
    }
}

Original Author amynbe Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

Siddharth

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment