Comparable and Comparator Implementation in Java with Example [Interview Question]

Sdílet
Vložit
  • čas přidán 30. 04. 2020
  • In this video of Comparable and comparator implementation in java we are going to see the implementation of comparator and comparable
    Udemy Course of Code Decode on Microservice k8s AWS CICD link:
    openinapp.co/udemycourse
    Course Description Video :
    yt.openinapp.co/dmjvd
    - Comparable and Comparable in Java
    - Difference between Comparator and Comparable
    - Example of Comparator and Comparable
    - Create getters and setters
    - toString() method
    - Creating List and adding values in List
    - Collection.sort method to sort the List
    - When to use Comparable and when to use Comparator
    - compareTo() method
    - How to use comparable
    - How to use Comparator
    #comparable #comparator #comprableandcomparator
    comparable and comparator program in java. Complete step by step by guide to implement comparable as well as comparator in java
    Why there is comparable and comparator in java
    • Why comparable and com...
    Comparable vs Comparator
    • Comparable VS Comparat...
    -------------------------------------------------------------------------------------------------------------------------------------
    Code Decode Playlists
    Most Asked Core Java Interview Questions and Answers : • Core Java frequently a...
    Advance Java Interview Questions and Answers : • Advance Java Interview...
    Java 8 Interview Questions and Answers : • Java 8 Interview Quest...
    Hibernate Interview Questions and Answers : • Hibernate Interview Qu...
    Spring Boot Interview Questions and Answers : • Advance Java Interview...
    Angular Playlist : • Angular Course Introdu...
    GIT : • GIT
    -------------------------------------------------------------------------------------------------------------------------------------
    Subscriber and Follow Code Decode
    Subscriber Code Decode : czcams.com/users/CodeDecode?...
    Linkedin : / codedecodeyoutube
    Instagram : / codedecode25
    --------------------------------------------------------------------------------------------------------------------------------------
  • Věda a technologie

Komentáře • 81

  • @vrushabhulle9374
    @vrushabhulle9374 Před rokem +5

    thanks mam this was same example i have for my technical coding round and i have succesfully cleared it along with explanation you have given. keep up the good work

    • @CodeDecode
      @CodeDecode  Před rokem

      Many congratulations Vrushab 👏👏👏👏. Keep learning keep shining Man 👍👍

  • @bhavinmajethia7070
    @bhavinmajethia7070 Před 8 dny

    Awesome ! Keep up the good work

  • @SaurabhKumar-fo6zp
    @SaurabhKumar-fo6zp Před rokem +1

    Best channel to prepare for java interviews.

  • @AvinashKumar-ps8wl
    @AvinashKumar-ps8wl Před 3 lety +2

    detailed and clear explaination of concepts !!

  • @rohitnain2815
    @rohitnain2815 Před 3 lety +1

    Amazing video and nicely explained. Thank you.

  • @gyanprakash302
    @gyanprakash302 Před 2 lety +1

    I now binge watch your videos even while eating, thanks for such amazing content !

    • @CodeDecode
      @CodeDecode  Před 2 lety

      Thanks Gyan 🙂👍. Hope you reach to your dream job 👍👍keep learning keep rocking 🎸🎶🎶🎸🎶🎶

  • @basavarajappamc9547
    @basavarajappamc9547 Před rokem +1

    Every topic is explained very well.Thanks a lot

  • @akash20931
    @akash20931 Před 4 lety +4

    beautifully explained, such a simple understanding of complex topics.

  • @shankardayal6928
    @shankardayal6928 Před 3 lety

    What you do with compare method of comparator interface can be achieved with changing logic of compareTo method of comparable interface.
    Correct me if wrong?
    Then what is benefit of using comparator interface over comparable interface?

  • @sagarmeena0210
    @sagarmeena0210 Před 3 lety +1

    you are very good with your explanation with example

  • @priyankagupta118
    @priyankagupta118 Před 2 lety +1

    Great Content!! Thanks!

  • @sairanganatham7511
    @sairanganatham7511 Před 2 lety +1

    Excellent videos by you

  • @ashubtech9911
    @ashubtech9911 Před 3 lety +1

    Opened to learn this topic....and after completing the video i remember only ur voice...🥰

  • @kritikashukla9937
    @kritikashukla9937 Před 3 lety +1

    Thank you, this was helpful

  • @coincidentIndia
    @coincidentIndia Před 2 lety +8

    since Comparator is a Functional Interface, we can use Comparator.compare(e1,e2) directly in the Collections.sort. Code will be like Collections.sort(employeeList, (e1,e2)->e1.getEmployeeName().compareTo(e2.getEmployeeName()))

  • @vrushaliyadav1023
    @vrushaliyadav1023 Před 3 lety +1

    Can use comparator without implementation of comparable interface?

  • @alladisindhuja2872
    @alladisindhuja2872 Před 3 lety +1

    Thanks alot ..good explanation ..

  • @kazaasekhar
    @kazaasekhar Před 3 lety +1

    very nice and excellent tutotial

  • @naveensingh7261
    @naveensingh7261 Před 2 lety +2

    One small suggestion. If you are using java8 or above version then you can optimize your code by lambda expression.

    • @CodeDecode
      @CodeDecode  Před 2 lety +1

      czcams.com/play/PLyHJZXNdCXsdeusn4OM33415DCMQ6sUKy.html

  • @afreedkhaja1675
    @afreedkhaja1675 Před 3 lety +2

    You have a such a cute voice 😍😍

  • @zabhashdamha
    @zabhashdamha Před 2 lety +1

    Thank you for making it easy to learn these concept.

  • @jskr456
    @jskr456 Před rokem +1

    well explained!!

  • @rupadevigujjari2202
    @rupadevigujjari2202 Před 3 lety +1

    Exellent :)

  • @krishnavamsireddy6098
    @krishnavamsireddy6098 Před 2 lety +1

    Thank you sister 🌿🌿🌿

    • @CodeDecode
      @CodeDecode  Před 2 lety

      Our pleasure Krishnavamsi🙂🙂👍👍

  • @GauravKumar-zg7kw
    @GauravKumar-zg7kw Před rokem +3

    1:50 - can you please explain what is the exact value that is expected in this.id and o.id ?

    • @anubhavsingh2916
      @anubhavsingh2916 Před rokem

      Me bhi yahi dhundh raha hu but koi bhi apni video isse explain nahi kar raha

    • @prashantanand8108
      @prashantanand8108 Před rokem

      bhai sbsei shi tarika sout karke dkhlei kya aa rha hai khud pata chl jaayega yei sb bkaar hai inhei padhana nhi aata Durgasoft best hai agar java sikhni hai to vo time taking hai but worth it hai

  • @g.mohanphanindra
    @g.mohanphanindra Před rokem +1

    Thank you

  • @rohitgade3642
    @rohitgade3642 Před 3 lety +2

    nice explanation mam, I have a query I tried using by name and by address it is not working can u help with that?

    • @CodeDecode
      @CodeDecode  Před 3 lety

      Can you please elaborate your issue so that I can help you out

  • @sureshgarine
    @sureshgarine Před 3 lety

    can u please explain elaborately regarding with better examples, this looks like it went fast forward

  • @vishnuprasad-ut5if
    @vishnuprasad-ut5if Před 5 měsíci

    The way u say java error thrown at our faces I feel it actually 😂

  • @flight_of_phoenix
    @flight_of_phoenix Před 3 lety +1

    I want to know how comparison is done. If first object is greater than the second then the compareTo method returns positive else negative and 0 if both are same. How these come into play when we are implementing either comparable or comparator? How the sorting is done based on that

  • @shivanishivu32
    @shivanishivu32 Před 3 lety +2

    great videos. Are you gujarati?

    • @CodeDecode
      @CodeDecode  Před 3 lety

      Yes I am 😊🤓. Though I am an Indian too. How did u catch that though? M curious to know that 🙃

  • @muthukumara8792
    @muthukumara8792 Před 3 lety +1

    Mam can we use collection.sort( ) instead of array.sort( )?

    • @CodeDecode
      @CodeDecode  Před 3 lety +3

      You can but collection. Sort calls list.sort() which internally calls arrays.sort() . In directly you are doing the same thing. In turn collection.sort() is slower. Hence prefer using array.sort()

    • @ayyappag7097
      @ayyappag7097 Před 2 lety

      @@CodeDecode Is it ok to use Arrays.sort() method for List object. if not , which one is better to use in this case ?

  • @immortalhuman7085
    @immortalhuman7085 Před 3 lety +2

    Companies want to see implementation of these comparator and comparable interfaces through lambda express.

    • @CodeDecode
      @CodeDecode  Před 3 lety +1

      We have covered that in java 8 series many times if you have noticed. Even we have used comparator to sort in descending order in that java 8 playlist using lambda expression

    • @debaduttadas2331
      @debaduttadas2331 Před 3 lety

      Easy .While Passing the arguments in sort method of Arrays class or Treeset constructor or Tree Map constructor instead of passing Comparator object You can pass them as lambda expressions.Remember comparater takes 2 arguments so accordingly you can give the body of your lambda by doing Your own sorting(customized).Be clear of Lambdas first then you can easily apply here .All The Best

  • @abhijitkulkarni3563
    @abhijitkulkarni3563 Před 2 lety +1

    How can we sort words in a sentence first by length of words and if length matches then it should sort alphabetically.
    For example "Apple and grape are not vagetables"
    Output should be "and are not apple grape vagetables"
    Can you create a video on this?
    Note :- This question was asked in an interview!

    • @CodeDecode
      @CodeDecode  Před 2 lety

      Nice question Abhijit we will put video on this 👍🙂

    • @abhijitkulkarni3563
      @abhijitkulkarni3563 Před 2 lety

      @@CodeDecode
      Below is the code snippet which I figured out , see if you can optimize more?
      // String sentence="Apple and grape are not vagetables";
      //String sentence="Java8 gives us the opportunity";
      String sentence="the examples in this article are available over on GitHub";
      List data= Arrays.asList(sentence.split("\\s"));
      Map info=new HashMap();
      data.forEach(word-> {
      if(info.get(word.length())==null){
      info.put(word.length(),new ArrayList(Arrays.asList(word)));
      }else{
      List existingList=info.get(word.length());
      existingList.add(word);
      info.putIfAbsent(word.length(),existingList);
      }
      });
      info.entrySet().stream().forEach(key-> {
      System.out.print(key.getValue().stream().sorted().collect(Collectors.toList()));
      });

  • @dystopianNinja1289
    @dystopianNinja1289 Před 3 lety

    Hi , when i tried to run the code i got the following output for the comparator part - [code_decode.Employee@15db9742, code_decode.Employee@6d06d69c, code_decode.Employee@7852e922, code_decode.Employee@4e25154f]

  • @nidhichugh1527
    @nidhichugh1527 Před 3 lety +3

    Ma'am can u please tell how to sort using name while using Comparable
    Because when I'm doing this.name - o.name
    It is giving an error that - operator is undefined for argument type

    • @dileepgowda6586
      @dileepgowda6586 Před 3 lety

      use compareToIgnoreCase mathod and return in compareTo method.

    • @dileepgowda6586
      @dileepgowda6586 Před 3 lety

      userName.compareToIgnoreCase(user.userName);

    • @dileepgowda6586
      @dileepgowda6586 Před 3 lety

      public int compareTo(User user) {
      return userName.compareToIgnoreCase(user.userName);
      }

  • @harshadaraut4096
    @harshadaraut4096 Před 2 lety

    Will you please help me to solve one question with java 8
    Sort Emoployees based on their salaries, if salary is equal sort using their name
    Eg.
    Id Name Salary
    1 Danish 5000
    2 Omkar 3000
    3 Om 3000
    4 Akash 2000
    So the result will be
    4 Akash 2000
    3 Om 3000
    2 Omkar 3000
    1 Danish 5000
    Asked in interview..

    • @skyhi9383
      @skyhi9383 Před rokem

      import java.util.*;
      import java.util.stream.Collectors;
      class Employee{
      int id;
      String name;
      double salary;
      Employee(int id,String name,double salary){
      this.id = id;
      this.name = name;
      this.salary = salary;
      };
      @Override
      public String toString() {
      return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
      }
      };
      class HelloWorld {
      public static void main(String[] args) {
      System.out.println("Hello, World!");
      Employee [] employees = new Employee[4];
      employees[0] = new Employee(1,"Danish",5000);
      employees[1] = new Employee(2,"Omkar",3000);
      employees[2] = new Employee(3,"Om",3000);
      employees[3] = new Employee(4,"Akash",2000);
      // Comparator values
      Comparator c =(e1,e2)->{
      if(e1.salary == e2.salary) return e1.name.compareTo(e2.name);
      else if(e1.salary > e2.salary) return 1;
      return -1;
      };
      List result = Arrays.stream(employees).sorted(c).collect(Collectors.toList());
      System.out.println(result);

      }
      }

  • @palashpullarwar2581
    @palashpullarwar2581 Před 3 lety +2

    Comparator nahi samjha

    • @CodeDecode
      @CodeDecode  Před 3 lety +1

      No worries. Where you missed ? Not able to understand anonymous class ?

  • @sairamaraju6652
    @sairamaraju6652 Před 2 lety +1

    Can I get ur mail

    • @CodeDecode
      @CodeDecode  Před 2 lety

      It's codedecodebusiness@gmail.com