Comparator for Pair in Kotlin












0














I can write comparator for specialized types in Kotlin
class Comparator() : kotlin.Comparator<Pair<Double, Int>>

But how can I write comparator using generics for all possible types that extend Comparable<...>?










share|improve this question


















  • 2




    kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/…
    – JB Nizet
    Nov 22 at 19:57
















0














I can write comparator for specialized types in Kotlin
class Comparator() : kotlin.Comparator<Pair<Double, Int>>

But how can I write comparator using generics for all possible types that extend Comparable<...>?










share|improve this question


















  • 2




    kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/…
    – JB Nizet
    Nov 22 at 19:57














0












0








0







I can write comparator for specialized types in Kotlin
class Comparator() : kotlin.Comparator<Pair<Double, Int>>

But how can I write comparator using generics for all possible types that extend Comparable<...>?










share|improve this question













I can write comparator for specialized types in Kotlin
class Comparator() : kotlin.Comparator<Pair<Double, Int>>

But how can I write comparator using generics for all possible types that extend Comparable<...>?







generics kotlin comparator






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 19:51









Alex Row

337




337








  • 2




    kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/…
    – JB Nizet
    Nov 22 at 19:57














  • 2




    kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/…
    – JB Nizet
    Nov 22 at 19:57








2




2




kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/…
– JB Nizet
Nov 22 at 19:57




kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/…
– JB Nizet
Nov 22 at 19:57












2 Answers
2






active

oldest

votes


















1














You can create comparator, using helping functions - compareBy, compareByDescending, naturalOrder, reverseOrder https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/index.html



For example:



val map = mapOf<Int, String>()
// ... add values to the map
val sortedMap: SortedMap<Int, String> = map.toSortedMap(compareByDescending { it })


And for your case:



val comparator = compareBy<Pair<Double, Int>> { it.first }


Custom comparator:



class CustomComparator<T: Comparable<T>> : Comparator<T> {
override fun compare(o1: T, o2: T): Int {
return o1.compareTo(o2)
}
}





share|improve this answer























  • That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
    – Alex Row
    Nov 22 at 21:46










  • Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
    – Sergey
    Nov 23 at 7:54



















0














You can use the following function to combine two comparators into a pair comparator which compares the first value of a pair with the first comparator and then the second value with the second comparator:



fun <T, U> pairComparator(
firstComparator: Comparator<T>,
secondComparator: Comparator<U>
): Comparator<Pair<T, U>> =
compareBy(firstComparator) { p: Pair<T, U> -> p.first }
.thenBy(secondComparator) { p: Pair<T, U> -> p.second }


Then you use it as following:



val source = listOf(1 to 2.3, 1 to 2.0, 0 to 3.0)
val result1 = source.sortedWith(pairComparator(naturalOrder(), naturalOrder()))
println(result1) // [(0, 3.0), (1, 2.0), (1, 2.3)]

val result2 = source.sortedWith(pairComparator(naturalOrder(), reverseOrder()))
println(result2) // [(0, 3.0), (1, 2.3), (1, 2.0)]


See the full code here: https://pl.kotl.in/BkMOzb8CX






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437312%2fcomparator-for-pair-in-kotlin%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    You can create comparator, using helping functions - compareBy, compareByDescending, naturalOrder, reverseOrder https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/index.html



    For example:



    val map = mapOf<Int, String>()
    // ... add values to the map
    val sortedMap: SortedMap<Int, String> = map.toSortedMap(compareByDescending { it })


    And for your case:



    val comparator = compareBy<Pair<Double, Int>> { it.first }


    Custom comparator:



    class CustomComparator<T: Comparable<T>> : Comparator<T> {
    override fun compare(o1: T, o2: T): Int {
    return o1.compareTo(o2)
    }
    }





    share|improve this answer























    • That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
      – Alex Row
      Nov 22 at 21:46










    • Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
      – Sergey
      Nov 23 at 7:54
















    1














    You can create comparator, using helping functions - compareBy, compareByDescending, naturalOrder, reverseOrder https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/index.html



    For example:



    val map = mapOf<Int, String>()
    // ... add values to the map
    val sortedMap: SortedMap<Int, String> = map.toSortedMap(compareByDescending { it })


    And for your case:



    val comparator = compareBy<Pair<Double, Int>> { it.first }


    Custom comparator:



    class CustomComparator<T: Comparable<T>> : Comparator<T> {
    override fun compare(o1: T, o2: T): Int {
    return o1.compareTo(o2)
    }
    }





    share|improve this answer























    • That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
      – Alex Row
      Nov 22 at 21:46










    • Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
      – Sergey
      Nov 23 at 7:54














    1












    1








    1






    You can create comparator, using helping functions - compareBy, compareByDescending, naturalOrder, reverseOrder https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/index.html



    For example:



    val map = mapOf<Int, String>()
    // ... add values to the map
    val sortedMap: SortedMap<Int, String> = map.toSortedMap(compareByDescending { it })


    And for your case:



    val comparator = compareBy<Pair<Double, Int>> { it.first }


    Custom comparator:



    class CustomComparator<T: Comparable<T>> : Comparator<T> {
    override fun compare(o1: T, o2: T): Int {
    return o1.compareTo(o2)
    }
    }





    share|improve this answer














    You can create comparator, using helping functions - compareBy, compareByDescending, naturalOrder, reverseOrder https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.comparisons/index.html



    For example:



    val map = mapOf<Int, String>()
    // ... add values to the map
    val sortedMap: SortedMap<Int, String> = map.toSortedMap(compareByDescending { it })


    And for your case:



    val comparator = compareBy<Pair<Double, Int>> { it.first }


    Custom comparator:



    class CustomComparator<T: Comparable<T>> : Comparator<T> {
    override fun compare(o1: T, o2: T): Int {
    return o1.compareTo(o2)
    }
    }






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 22 at 20:21

























    answered Nov 22 at 20:02









    Sergey

    1,97621324




    1,97621324












    • That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
      – Alex Row
      Nov 22 at 21:46










    • Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
      – Sergey
      Nov 23 at 7:54


















    • That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
      – Alex Row
      Nov 22 at 21:46










    • Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
      – Sergey
      Nov 23 at 7:54
















    That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
    – Alex Row
    Nov 22 at 21:46




    That's good, but I wanted for some implementation of generic class which can be used, for example, both for Pair<Int, String> and for Pair<Long, Double>
    – Alex Row
    Nov 22 at 21:46












    Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
    – Sergey
    Nov 23 at 7:54




    Why compareBy and other helper functions don't work for you? You can use it to create Comparator of any Pairs.
    – Sergey
    Nov 23 at 7:54













    0














    You can use the following function to combine two comparators into a pair comparator which compares the first value of a pair with the first comparator and then the second value with the second comparator:



    fun <T, U> pairComparator(
    firstComparator: Comparator<T>,
    secondComparator: Comparator<U>
    ): Comparator<Pair<T, U>> =
    compareBy(firstComparator) { p: Pair<T, U> -> p.first }
    .thenBy(secondComparator) { p: Pair<T, U> -> p.second }


    Then you use it as following:



    val source = listOf(1 to 2.3, 1 to 2.0, 0 to 3.0)
    val result1 = source.sortedWith(pairComparator(naturalOrder(), naturalOrder()))
    println(result1) // [(0, 3.0), (1, 2.0), (1, 2.3)]

    val result2 = source.sortedWith(pairComparator(naturalOrder(), reverseOrder()))
    println(result2) // [(0, 3.0), (1, 2.3), (1, 2.0)]


    See the full code here: https://pl.kotl.in/BkMOzb8CX






    share|improve this answer


























      0














      You can use the following function to combine two comparators into a pair comparator which compares the first value of a pair with the first comparator and then the second value with the second comparator:



      fun <T, U> pairComparator(
      firstComparator: Comparator<T>,
      secondComparator: Comparator<U>
      ): Comparator<Pair<T, U>> =
      compareBy(firstComparator) { p: Pair<T, U> -> p.first }
      .thenBy(secondComparator) { p: Pair<T, U> -> p.second }


      Then you use it as following:



      val source = listOf(1 to 2.3, 1 to 2.0, 0 to 3.0)
      val result1 = source.sortedWith(pairComparator(naturalOrder(), naturalOrder()))
      println(result1) // [(0, 3.0), (1, 2.0), (1, 2.3)]

      val result2 = source.sortedWith(pairComparator(naturalOrder(), reverseOrder()))
      println(result2) // [(0, 3.0), (1, 2.3), (1, 2.0)]


      See the full code here: https://pl.kotl.in/BkMOzb8CX






      share|improve this answer
























        0












        0








        0






        You can use the following function to combine two comparators into a pair comparator which compares the first value of a pair with the first comparator and then the second value with the second comparator:



        fun <T, U> pairComparator(
        firstComparator: Comparator<T>,
        secondComparator: Comparator<U>
        ): Comparator<Pair<T, U>> =
        compareBy(firstComparator) { p: Pair<T, U> -> p.first }
        .thenBy(secondComparator) { p: Pair<T, U> -> p.second }


        Then you use it as following:



        val source = listOf(1 to 2.3, 1 to 2.0, 0 to 3.0)
        val result1 = source.sortedWith(pairComparator(naturalOrder(), naturalOrder()))
        println(result1) // [(0, 3.0), (1, 2.0), (1, 2.3)]

        val result2 = source.sortedWith(pairComparator(naturalOrder(), reverseOrder()))
        println(result2) // [(0, 3.0), (1, 2.3), (1, 2.0)]


        See the full code here: https://pl.kotl.in/BkMOzb8CX






        share|improve this answer












        You can use the following function to combine two comparators into a pair comparator which compares the first value of a pair with the first comparator and then the second value with the second comparator:



        fun <T, U> pairComparator(
        firstComparator: Comparator<T>,
        secondComparator: Comparator<U>
        ): Comparator<Pair<T, U>> =
        compareBy(firstComparator) { p: Pair<T, U> -> p.first }
        .thenBy(secondComparator) { p: Pair<T, U> -> p.second }


        Then you use it as following:



        val source = listOf(1 to 2.3, 1 to 2.0, 0 to 3.0)
        val result1 = source.sortedWith(pairComparator(naturalOrder(), naturalOrder()))
        println(result1) // [(0, 3.0), (1, 2.0), (1, 2.3)]

        val result2 = source.sortedWith(pairComparator(naturalOrder(), reverseOrder()))
        println(result2) // [(0, 3.0), (1, 2.3), (1, 2.0)]


        See the full code here: https://pl.kotl.in/BkMOzb8CX







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 23 at 22:43









        Ilya

        8,96943056




        8,96943056






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437312%2fcomparator-for-pair-in-kotlin%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            How to ignore python UserWarning in pytest?

            Alexandru Averescu