#95 Comparator vs Comparable in Java

Поділитися
Вставка
  • Опубліковано 1 січ 2025

КОМЕНТАРІ • 134

  • @naul2k74
    @naul2k74 Рік тому +43

    You literally teach and explain everything about sorting with object in 15 mins that my professor wasn't able to do in 2 hours. Good job and keep doing these things because it's really helpful and valuable to a fresher like me

    • @jnslzr
      @jnslzr 2 місяці тому +1

      same, our teacher here literally sent us to read javadocs =)

  • @Noah-zc6mv
    @Noah-zc6mv Рік тому +26

    So glad you're updating your older videos. Helpful as always! 😁

  • @suhailsharieff155
    @suhailsharieff155 Рік тому +8

    Navin sir.... Really fond of u..... I sat for 5 hrs to understand it.... Now im crystal clear

  • @gurrammahenderreddy4586
    @gurrammahenderreddy4586 Рік тому +4

    TASK :
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    class Hello {
    public static void main(String a[]) {
    Comparator com = new Comparator() {
    public int compare(String i, String j)
    {
    if(i.length() < j.length())
    return 1;
    else
    return -1;
    }
    };
    List names = new ArrayList();
    names.add("Navin");
    names.add("Navin Reddy");
    names.add("Telusko");
    names.add("Navin Telusko");
    Collections.sort(names, com);
    System.out.println(names);
    }
    }

  • @AmeyChittar
    @AmeyChittar Рік тому +6

    Hi Navin. as usual great video.. but most importantly comparator and comparable have always been things ive never understood.... until now.. the way you have explained is amazing and always wait for your amazing videos. and by the way the growth of your presentation and teaching skills have become better and better and we love it. Thanks a lot and will be waiting for lots more videos.

  • @Democracy_Manifest
    @Democracy_Manifest Рік тому +18

    Good video. Thanks for leaving in the errors so we can learn.

  • @varsheethtv
    @varsheethtv Рік тому +6

    The last 2 mins are very insightful!! 😍😍

  • @rhea1149
    @rhea1149 Рік тому +4

    best java instructor i’ve ever come across

  • @tarekabushaheen7593
    @tarekabushaheen7593 7 місяців тому +1

    10/10 video and demonstration, absolutely love the dynamic, following along and coding beside you helps to learn efficiently

  • @karanraut4417
    @karanraut4417 Рік тому

    @telusko I loved your teaching style Naveen Reddy Sir,
    It is not necessary for a Comparator to return -1 or 1 it can actually return any negative or positive integer only the sign matters. even 0 is allowed i guess.
    this caused me confusion but you should have also mentioned it at the end for more nerdy people.
    package java4AdvancedCollections;
    import java.util.TreeSet;
    public class TreeSetExample {
    public static void main(String[] args) {
    // Creating a TreeSet of integers (natural ordering)
    TreeSet treeSet = new TreeSet();
    // Adding elements to the TreeSet
    treeSet.add(10);
    treeSet.add(5);
    treeSet.add(20);
    treeSet.add(15);
    // Printing the TreeSet (elements will be in ascending order)
    System.out.println("TreeSet: " + treeSet);
    // Creating a TreeSet with a custom comparator for descending order
    TreeSet descendingTreeSet = new TreeSet((a, b) -> {
    if (a > b) {
    return -2;
    } else {
    return 2;
    }
    });
    // Adding elements to the descending TreeSet
    descendingTreeSet.add(10);
    descendingTreeSet.add(5);
    descendingTreeSet.add(20);
    descendingTreeSet.add(15);
    // Printing the descending TreeSet (elements will be in descending order)
    System.out.println("Descending TreeSet: " + descendingTreeSet);
    // Performing operations specific to NavigableSet interface
    System.out.println("Ceiling of 12: " + treeSet.ceiling(12));
    System.out.println("Floor of 12: " + treeSet.floor(12));
    }
    }

  • @dypsking3414
    @dypsking3414 Рік тому +3

    Thank you Mr.
    You made it very simple and easy!

  • @xacademia9646
    @xacademia9646 Рік тому +37

    you know the person teaching you about java is legit when he is bald hehe. subscribed :)

    • @tsum3489
      @tsum3489 Рік тому +1

      My teacher in University who's teaching us java is also bald🤣 and he even looks so much like this youtuber!!

  • @vikrantsingh2804
    @vikrantsingh2804 9 місяців тому

    I must say this was one of the best videos explaining comparator and comparable concept.

  • @inspiredomkar1239
    @inspiredomkar1239 Рік тому +2

    Logic to sort elements based on the length of the string
    import java.util.Comparator;
    import java.util.*;
    class Solution {
    public static void main(String[] args) {

    Comparator com = new Comparator(){
    public int compare(String a , String b){
    if(a.length() > b.length())
    return 1;
    else
    return -1;
    }
    };
    List nums = new ArrayList();
    nums.add("Python");
    nums.add("C++");
    nums.add("Java");
    nums.add("Django");
    nums.add("SpringBoot");
    nums.add("Spring");
    Collections.sort(nums , com);
    System.out.println(nums);
    }
    }

  • @pratikkumarsingh8114
    @pratikkumarsingh8114 Рік тому

    Great, got my concepts cleared . Thank you , sir!!!👍👍👍👍👍👍👍👍👍👍👍👍👍👍

  • @ekanshmishra4517
    @ekanshmishra4517 3 місяці тому +2

    I have been struggling to understand this for long and this video is what it was required to get it cleared. Thank you @NavinSir #Telusko

  • @moviecraze6079
    @moviecraze6079 6 місяців тому

    Heck of a video! I have been trying to understand the differences for a long time, finally you cleared all of my doubts.

  • @beinghuman63393
    @beinghuman63393 Рік тому +1

    Excellent ❤❤ , feeling enjoyed the functional usage at the end

  • @SphereofTime
    @SphereofTime 3 місяці тому

    comparable and so no?1:00

  • @LeahThomas-is4hm
    @LeahThomas-is4hm 10 днів тому

    Great video sir..telling in depth concepts simply for understanding..thanks a lot

  • @abhinavmishra9690
    @abhinavmishra9690 Рік тому +2

    Understood today the real concept behind comparator and comparable

  • @adityarao7249
    @adityarao7249 Рік тому +1

    Love your videos, learn new thing every time.

  • @Manjot_singh2002
    @Manjot_singh2002 10 місяців тому +1

    7:28
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class first {
    public static void main(String[] args) throws IOException
    {
    Comparator comp = new Comparator() {
    public int compare(String s, String t) {
    if (s.length() < t.length())
    return 1;
    else
    return -1;
    // throw new UnsupportedOperationException("Unimplemented method 'compare'");
    }
    };
    List col=new ArrayList();
    col.add("aaaaa");
    col.add("aa");
    col.add("aaaa");
    col.add("a");
    Collections.sort(col, comp);
    System.out.println(col);
    }
    }

  • @deepthimalepatiii247
    @deepthimalepatiii247 10 місяців тому

    Reddy ji! No words Thanks for your explanation

  • @uLise4Life
    @uLise4Life Рік тому +1

    Had to watch an entire tutorial just because I thought I don't undertand java. After this video. i'm like OH MY GOD !!!!!!!!!

  • @priyanshukhullar-tc7ss
    @priyanshukhullar-tc7ss Рік тому +1

    Awesome guruji shukriya

  • @franciscomambo4120
    @franciscomambo4120 9 місяців тому

    Just discovered this video and the explanation is awesome, it almost blew my mind

  • @sharabugnanesh3098
    @sharabugnanesh3098 Рік тому +1

    7:20
    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    public class compa {
    public static void main(String[] args) {
    Comparator y = new Comparator() {
    public int compare(String i, String j) {
    if (i.length() > j.length())
    return 1;
    else
    return -1;
    }
    };
    List names = new ArrayList();
    names.add("Gnani");
    names.add("Gnan");
    names.add("Chapathi");
    names.add("Gnanesh");
    names.add("navin mava");
    Collections.sort(names, y);
    System.out.println(names);
    }
    }

    • @codework2434
      @codework2434 Рік тому +1

      Line no: 8 --> You have to specify Comparator on right side as well, its compulsory 3:03 . But I dono why it works without it.

    • @sharabugnanesh3098
      @sharabugnanesh3098 Рік тому +1

      ​​@@codework2434 it's new update from official java it's unnecessary to mention on creating object of Comparator But in case of anonymous class we should!
      do you understand?

    • @codework2434
      @codework2434 Рік тому

      @@sharabugnanesh3098 So, in your code above you left to mention the type, right ?

    • @sharabugnanesh3098
      @sharabugnanesh3098 Рік тому +1

      @@codework2434 yes I need to mention at left

    • @codework2434
      @codework2434 Рік тому +1

      @@sharabugnanesh3098 Thanks about the "official java update"

  • @Sumanth_Siddareddy
    @Sumanth_Siddareddy Рік тому +1

    thanks for your explanation, sir. It helps me to understand comparable and comparator.

  • @ManojPatil-z8m
    @ManojPatil-z8m 5 місяців тому

    Hats off to you, sir! 🙌

  • @vinethasuresh3488
    @vinethasuresh3488 Рік тому

    wonderful video, it helps me to understand the concept very clear . Example you are providing is just awesome sir. keep doing these kind of videos sir. thanks a lot.

  • @emmaruhcheva3658
    @emmaruhcheva3658 7 місяців тому

    amazing video, gave me the summary i needed!

  • @shriharis.s3296
    @shriharis.s3296 4 місяці тому +1

    Here i have a doubt. Comparable is a functional interface. So we can override onlt compareTo() method and it is fine. But Comparator method is not a functional interface. How can we just override only menthod which is compare() and Java dosen't gives an error?

  • @mikedelta658
    @mikedelta658 11 місяців тому

    Now, I understood those concepts. Thanks

  • @shraddhashetty8659
    @shraddhashetty8659 Рік тому +4

    Sorting the String based on the length:
    public class PractComparator {
    public static void main(String[] arg) {
    Comparator com = new Comparator() {
    @Override
    public int compare(String o1, String o2) {
    return o1.length() - o2.length();
    }
    };
    List fruit = new ArrayList();
    fruit.add("Banana");
    fruit.add("Mandarin");
    fruit.add("PineApple");
    fruit.add("Apple");

    Collections.sort(fruit,com);

    System.out.println(fruit);

    }

    }

  • @stargaming3103
    @stargaming3103 Рік тому +3

    Sir what is meaning of 1 and -1 . I didn't understand that

  • @yusrax3
    @yusrax3 3 місяці тому +1

    finally understood thanks!

  • @student_03
    @student_03 Рік тому +1

    thats a great video
    covered all that i needed thank you

  • @HitRespawn
    @HitRespawn 11 днів тому

    why we create List nums = new ArrayList
    and not ArrayList nums = new ArrayList
    I am confused please help

  • @abrorallaberganov6293
    @abrorallaberganov6293 6 місяців тому

    Great Explanation. Thanks

  • @iamspidysa
    @iamspidysa 20 днів тому

    7:26
    ArrayList arrS = new ArrayList();
    arrS.add("ABC");
    arrS.add("ABCDE");
    arrS.add("A");
    arrS.add("XYZABCDEF");
    arrS.add("AS");
    Comparator comS = new Comparator() {
    public int compare(String i, String j){
    if((i.length())>(j.length()))
    return 1;
    else
    return -1;
    }
    };
    Collections.sort(arrS,comS);
    System.out.println(arrS);

  • @sai-dx1vb
    @sai-dx1vb Рік тому +1

    How you intantiated the comparator because comparator is an interface and we cannot instantiate interface?

    • @eofvoid122
      @eofvoid122 18 днів тому

      That's because he used a lambda expression. Since Comparator is a Functional Interface (only has one abstract method to implement) you can use this special sintax to return an implementation of that interface. When using Lambda expressions, you only have to define how to implement the method.

  • @karanraut4417
    @karanraut4417 Рік тому

    @telusko it is not necessary for a Comparator to return -1 or 1 it can actually return any negative or positive integer only the sign matters.
    {even 0 is allowed i guess}

  • @tej3679
    @tej3679 Рік тому

    Thanks for the awesome explanation sir🎉

  • @gyanendramaurya1796
    @gyanendramaurya1796 10 місяців тому

    When i was a student in 2015 then also i used to come and watch java videos here. I now have almost 5 years of experience and when some Java work comes I come here again to refresh my memory. Thank you Navin. It feels like nostalgia sometimes watching your videos

  • @shankil2975
    @shankil2975 Рік тому

    Excellent video. Well explained. Can you add a comment here on how to sort based on more than one field? Say name and age assuming student names are duplicated. thanks

  • @aashuk
    @aashuk Рік тому

    Nice explanation. which IDE is that ? - got it. Visual Studio

  • @lxy2670
    @lxy2670 Рік тому

    i love you man. I finally got it!

  • @leonsvideos
    @leonsvideos Рік тому

    Great explanation, thank you so much!

  • @harshsuchak8370
    @harshsuchak8370 Рік тому

    Awesome Explanation!

  • @nischalofchrist
    @nischalofchrist Рік тому

    This is great explanation.

  • @soumyadeepchatterjee2189
    @soumyadeepchatterjee2189 Рік тому

    Very helpful, thank you.

  • @zeldaking2429
    @zeldaking2429 Рік тому

    Thank you. very clear and helpful!

  • @jeffro8807
    @jeffro8807 10 місяців тому

    your videos are awesome man

  • @Sriram-ii8oo
    @Sriram-ii8oo Місяць тому

    Thank you so much for this video ❤

  • @SugamSangeetwdSavita
    @SugamSangeetwdSavita Рік тому

    Do we always need to use Array List for comparator or can it be used for array also??

  • @lovemishra8137
    @lovemishra8137 6 місяців тому

    Nice explaination

  • @swacharahman5084
    @swacharahman5084 Рік тому

    This video is tooo goood. THANK you

  • @macedoedit5797
    @macedoedit5797 Рік тому

    Great video, thanks !

  • @GowthamE-l9r
    @GowthamE-l9r Рік тому

    Nuvu king mava🤗

  • @devabdul
    @devabdul Рік тому

    Thank you for valuable video ❤️

  • @akshaysilgari2097
    @akshaysilgari2097 Рік тому

    Great explanation

  • @sayantanhalder1056
    @sayantanhalder1056 5 місяців тому +1

    Sorting string by length
    package Collection;
    import java.util.*;
    public class SortStringByLen {
    public static void main(String[] args) {
    ArrayList ob = new ArrayList();
    ArrayList ob1 = new ArrayList();
    Comparator c1 = new Comparator() {
    public int compare(String i ,String j){
    if(i.length()>j.length()){
    return 1;
    }
    else{
    return -1;
    }
    }
    };
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the names: ");
    String str;
    int len;
    for(int i=0;i

  • @francksgenlecroyant
    @francksgenlecroyant Рік тому

    Navin Reddy never disappoints

  • @mrchaitu7
    @mrchaitu7 5 місяців тому

    Cannot make a static reference to the non-static field compare
    some times i am getting this error
    in quick fix i got add static
    static Comparator com = new Comparator() {
    then it solved

  • @srikanthatthota2151
    @srikanthatthota2151 8 місяців тому

    what if i try to implement Comparator on Student class, Navin reddy please explain this scenario

  • @SrinivasKumar-v3c
    @SrinivasKumar-v3c 7 місяців тому

    sir can u upload generics concept

  • @Vaishnav-zk2tf
    @Vaishnav-zk2tf Рік тому +2

    can any body tell me why return 1 and -1 is used .

  • @santoshchhetrithapa3573
    @santoshchhetrithapa3573 Рік тому

    thank u sir very helpful . all clear now . Okay I have

  • @awkward_adi
    @awkward_adi Рік тому

    Thank you so much for this.

  • @kidoo1567
    @kidoo1567 8 місяців тому

    Thanx jhonny

  • @ketansharma6955
    @ketansharma6955 Рік тому

    great video sir

  • @rahuljmd
    @rahuljmd 6 місяців тому

    Synopsis:
    If you want to give class the power to compare its object on its own then use Comparable otherwise use Comparator to define logic and pass its object in the Collections.sort() method....

  • @sumantagorai5880
    @sumantagorai5880 Рік тому

    1 for swap &
    -1 for no swap

  • @abhishekk3561
    @abhishekk3561 Рік тому

    I have a doubt .... how many times this swapping happens??

  • @ABHIJEETBHUJADE
    @ABHIJEETBHUJADE 4 місяці тому

    Can anyone help me waht is (a:) this label oprator why we use it

  • @-GANGUPALLIMAHAMMED
    @-GANGUPALLIMAHAMMED Рік тому

    Comparator is an interface so how object will created??

  • @nazeebahmed1050
    @nazeebahmed1050 Рік тому

    I have a quetion, why by returning 1 , the swapping is happenning?It doesn't make sense to me,plz explain

    • @audiomac
      @audiomac 10 місяців тому

      Hello! Returning 1 means that a is greater than b. Returning -1 means b is greater than a. Returning 0 means a equals b. I hope this helps!

  • @Bhimo-Bhima
    @Bhimo-Bhima 12 днів тому

    Radha Radha, Thanks Sir Very Helpfull

  • @hmmgmm2841
    @hmmgmm2841 Рік тому +1

    something meaningful to me

  • @abdulwadoodh5757
    @abdulwadoodh5757 Рік тому

    How did you replace nums to studs?

  • @hadse1234
    @hadse1234 Рік тому

    Very good videoes!

  • @ESECYogeshS
    @ESECYogeshS Рік тому +2

    Sir the collection is not a class it's an Interface

    • @Forty3Stories
      @Forty3Stories Рік тому

      Collections is a class but Collection is an interface 😊

  • @prateekgoel7154
    @prateekgoel7154 4 місяці тому

    Awesome video !!!

  • @bharath3207
    @bharath3207 Рік тому

    you are the best

  • @abhijeetkulkarni8246
    @abhijeetkulkarni8246 Рік тому

    Sir please try to make videos with white screen

  • @hygef-v4
    @hygef-v4 5 місяців тому

    thanks

  • @kareemaboud7750
    @kareemaboud7750 8 днів тому

    Last two minutes he said why not let's flex my knowledge

  • @ooogabooga5111
    @ooogabooga5111 8 місяців тому

    You are explaining saying sort() works using bubblesort in the background, which need not be the case, don't give wrong info. In case of java it uses, duel pivot quick sort sort alogithm. Why you pass in comparator, you are only letting the sort know how to compare the values, not the whole sorting.

  • @aminesaber467
    @aminesaber467 Рік тому +1

    import java.util.ArrayList;
    import java.util.Collection;
    import java.util.Collections;
    import java.util.Comparator;
    public class ChallengLQREA {

    public static void main(String[] args) {

    Comparator cmp = new Comparator() {
    public int compare(String o1, String o2) {

    if(o1.length() < o2.length())
    return -1;
    else
    return 1 ;
    }

    };



    ArrayList SortStrings = new ArrayList();
    SortStrings.add("Amine");
    SortStrings.add("Saberrr");
    SortStrings.add("Aichaa");
    SortStrings.add("Bahtiiii");

    Collections.sort(SortStrings,cmp );

    System.out.println(SortStrings);


    }

  • @AmitSingh-xc9qe
    @AmitSingh-xc9qe 4 місяці тому

    Thankyou sir

  • @priyanshukhullar-tc7ss
    @priyanshukhullar-tc7ss Рік тому +1

    Thankyou Reddy Ji lots of love.

  • @kashishswami3268
    @kashishswami3268 Рік тому

    14:03

  • @WolnośćUmysłu
    @WolnośćUmysłu Рік тому

    what is the IDE he is using?

  • @unemployedcse3514
    @unemployedcse3514 3 місяці тому

    awesome ❤

  • @mazerati935
    @mazerati935 Рік тому

    thanks

  • @sudeepbansal5234
    @sudeepbansal5234 Рік тому

    You are awesome 👏👏👏

  • @hiibuddy
    @hiibuddy Рік тому

    Ohh bhupendra jogi 😂😂😂

  • @ROSHAN-HARI-BALAJE
    @ROSHAN-HARI-BALAJE 6 місяців тому

    Ternary Operator ❌ Tatari Operator ✔

  • @Shri577
    @Shri577 5 місяців тому

    package basics;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class demo {
    public static void main(String[] args) {
    Comparator com = new Comparator()
    {

    public int compare(String i, String j) {

    if(i.length()