#95 Comparator vs Comparable in Java

Поделиться
HTML-код
  • Опубликовано: 17 янв 2023
  • Check out our courses:
    Spring and Microservices Weekend Live Batch : bit.ly/spring-live-weekend
    Coupon: TELUSKO10 (10% Discount)
    Master Java Spring Development : bit.ly/java-spring-cloud
    Udemy Courses:
    Java:- bit.ly/JavaUdemyTelusko
    Spring:- bit.ly/SpringUdemyTelusko
    Java For Programmers:- bit.ly/javaProgrammers
    For More Queries WhatsApp or Call on : +919008963671
    website : courses.telusko.com/
    In this lecture we will learn:
    - What is Comparator in Java?
    - How to give your implementation for sorting?
    - What is Comparable in Java?
    - Difference between Comparable & Comparator
    #1
    - From the Java 1.7 version, it is not compulsory to mention the generic type on the right-hand side if you have already mentioned it on the left-hand side.
    - A collection class has lots of methods. The collection class belongs to the util package.
    - We can sort a list or an ArrayList by using the method sort of collection class
    Collections.sort();
    - If we want to apply our own logic in sorting, then we have to use a comparator with sorting in collections.
    - Comparator is also an interface.
    - We have a method called compare() in the comparator interface.
    - We can use an interface by implementing a class or through an anonymous class.
    - Compare method works on an algorithm where it compares two values and then swaps them.
    Comparator Integer com= new Comparator Integer()
    {
    public int compare(Integer i, Integer j)
    {
    statements;
    }
    };
    - So, a comparator is an interface through which you can specify your own concept of sorting.
    #2
    - Integer class implements a Comparable interface. So by default, sort works for Integer.
    - If you want to do natural sorting on any other non-defined class, you can implement something called the Comparable.
    - Comparable is present in the lang package.
    - Comparable has a method known as compareTo().
    - You have to define the method comapreTo() in a class, that is implementing Comparable.
    class Student implements Comparable Student
    {
    public int compareTo( Student that){
    statements;
    }
    }
    Here, that is a variable.
    - We can also override the logic by using Comparator even if we have implements the Comparable interface.
    - Lambda expression can also be used with Comparator as it is a functional interface.
    #3
    Difference between Comparable & Comparator:
    - Comparable provides a single sorting sequence while the Comparator provides multiple sorting sequences.
    - In Comparable, actual gets modified while in Comparator, the original class does not get affected.
    - Comparable gives the compareTo() method for sorting while Comparator gives the compare() method to sort elements.
    Github repo : github.com/navinreddy20/Javac...
    Instagram : / navinreddyofficial
    Linkedin : / navinreddy20
    Discord : / discord
    Java:- bit.ly/JavaUdemyTelusko
    Spring:- bit.ly/SpringUdemyTelusko
    More Learning :
    Java :- bit.ly/3x6rr0N
    Python :- bit.ly/3GRc7JX
    Django :- bit.ly/3MmoJK6
    JavaScript :- bit.ly/3tiAlHo
    Node JS :- bit.ly/3GT4liq
    Rest Api :-bit.ly/3MjhZwt
    Servlet :- bit.ly/3Q7eA7k
    Spring Framework :- bit.ly/3xi7buh
    Design Patterns in Java :- bit.ly/3MocXiq
    Docker :- bit.ly/3xjWzLA
    Blockchain Tutorial :- bit.ly/3NSbOkc
    Corda Tutorial:- bit.ly/3thbUKa
    Hyperledger Fabric :- bit.ly/38RZCRB
    NoSQL Tutorial :- bit.ly/3aJpRuc
    Mysql Tutorial :- bit.ly/3thpr4L
    Data Structures using Java :- bit.ly/3MuJa7S
    Git Tutorial :- bit.ly/3NXyCPu
    Donation:
    PayPal Id : navinreddy20
    www.telusko.com
  • НаукаНаука

Комментарии • 117

  • @naul2k74
    @naul2k74 Год назад +27

    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

  • @Noah-zc6mv
    @Noah-zc6mv Год назад +18

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

  • @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 Год назад +15

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

  • @suhailsharieff155
    @suhailsharieff155 7 месяцев назад +5

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

  • @dypsking3414
    @dypsking3414 11 месяцев назад +2

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

  • @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.

  • @varsheethtv2459
    @varsheethtv2459 Год назад +5

    The last 2 mins are very insightful!! 😍😍

  • @tarekabushaheen7593
    @tarekabushaheen7593 2 месяца назад

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

  • @adityarao7249
    @adityarao7249 Год назад

    Love your videos, learn new thing every time.

  • @leonsvideos
    @leonsvideos Год назад

    Great explanation, thank you so much!

  • @zeldaking2429
    @zeldaking2429 Год назад

    Thank you. very clear and helpful!

  • @moviecraze6079
    @moviecraze6079 Месяц назад

    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

  • @pratikkumarsingh8114
    @pratikkumarsingh8114 10 месяцев назад +1

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

  • @Sumanth_Siddareddy
    @Sumanth_Siddareddy 8 месяцев назад

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

  • @nischalofchrist
    @nischalofchrist Год назад

    This is great explanation.

  • @student_03
    @student_03 11 месяцев назад +1

    thats a great video
    covered all that i needed thank you

  • @rhea1149
    @rhea1149 7 месяцев назад +2

    best java instructor i’ve ever come across

  • @devabdul
    @devabdul Год назад

    Thank you for valuable video ❤️

  • @tej3679
    @tej3679 10 месяцев назад

    Thanks for the awesome explanation sir🎉

  • @harshsuchak8370
    @harshsuchak8370 11 месяцев назад

    Awesome Explanation!

  • @franciscomambo4120
    @franciscomambo4120 4 месяца назад

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

  • @awkward_adi
    @awkward_adi Год назад

    Thank you so much for this.

  • @lxy2670
    @lxy2670 Год назад

    i love you man. I finally got it!

  • @vikrantsingh2804
    @vikrantsingh2804 4 месяца назад

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

  • @santoshchhetrithapa3573
    @santoshchhetrithapa3573 Год назад

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

  • @swacharahman5084
    @swacharahman5084 Год назад

    This video is tooo goood. THANK you

  • @emmaruhcheva3658
    @emmaruhcheva3658 Месяц назад

    amazing video, gave me the summary i needed!

  • @mikedelta658
    @mikedelta658 6 месяцев назад

    Now, I understood those concepts. Thanks

  • @abrorallaberganov6293
    @abrorallaberganov6293 23 дня назад

    Great Explanation. Thanks

  • @priyanshukhullar-tc7ss
    @priyanshukhullar-tc7ss 9 месяцев назад +1

    Awesome guruji shukriya

  • @hadse1234
    @hadse1234 Год назад

    Very good videoes!

  • @soumyadeepchatterjee2189
    @soumyadeepchatterjee2189 6 месяцев назад

    Very helpful, thank you.

  • @macedoedit5797
    @macedoedit5797 8 месяцев назад

    Great video, thanks !

  • @sai-dx1vb
    @sai-dx1vb 7 месяцев назад +1

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

  • @abhinavmishra9690
    @abhinavmishra9690 Год назад +2

    Understood today the real concept behind comparator and comparable

  • @ManojPatil-z8m
    @ManojPatil-z8m 4 дня назад

    Hats off to you, sir! 🙌

  • @deepthimalepatiii247
    @deepthimalepatiii247 5 месяцев назад

    Reddy ji! No words Thanks for your explanation

  • @lovemishra8137
    @lovemishra8137 Месяц назад

    Nice explaination

  • @shankil2975
    @shankil2975 9 месяцев назад

    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

  • @jeffro8807
    @jeffro8807 5 месяцев назад

    your videos are awesome man

  • @ketansharma6955
    @ketansharma6955 Год назад

    great video sir

  • @xacademia9646
    @xacademia9646 Год назад +33

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

    • @tsum3489
      @tsum3489 11 месяцев назад +1

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

  • @karanraut4417
    @karanraut4417 7 месяцев назад

    @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));
    }
    }

  • @aashuk
    @aashuk 9 месяцев назад

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

  • @akshaysilgari2097
    @akshaysilgari2097 7 месяцев назад

    Great explanation

  • @stargaming3103
    @stargaming3103 Год назад +2

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

  • @uLise4Life
    @uLise4Life 9 месяцев назад +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 !!!!!!!!!

  • @Progamer-fq8st
    @Progamer-fq8st 5 месяцев назад

    Code for sorting string based on length of the string:
    public static void main(String args[]) {

    Comparator com = new Comparator() {
    public int compare(String i, String j){
    if(i.length() > j.length()){
    return 1;
    }
    else{
    return -1;
    }
    }
    };
    List strs = new ArrayList();
    strs.add("Irene");
    strs.add("Seulgi");
    strs.add("Wendy");
    strs.add("Joy");
    strs.add("Yeri");
    Collections.sort(strs, com);
    System.out.println(strs);
    }
    // Output is [Joy, Yeri, Wendy, Irene, Seulgi]

  • @francksgenlecroyant
    @francksgenlecroyant 10 месяцев назад

    Navin Reddy never disappoints

  • @srikanthatthota2151
    @srikanthatthota2151 3 месяца назад

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

  • @kidoo1567
    @kidoo1567 3 месяца назад

    Thanx jhonny

  • @SugamSangeetwdSavita
    @SugamSangeetwdSavita 11 месяцев назад

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

    • @user-bb7ym2qk9h
      @user-bb7ym2qk9h 9 месяцев назад

      I think no
      We can use any collection
      Correct me if I am wrong

  • @gayathridhana1000
    @gayathridhana1000 Год назад

    Thanks

  • @hmmgmm2841
    @hmmgmm2841 Год назад +1

    something meaningful to me

  • @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

  • @abhishekk3561
    @abhishekk3561 Год назад

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

  • @mazerati935
    @mazerati935 Год назад

    thanks

  • @user-nl1rv9sm1o
    @user-nl1rv9sm1o 2 месяца назад

    sir can u upload generics concept

  • @bharath3207
    @bharath3207 10 месяцев назад

    you are the best

  • @karanraut4417
    @karanraut4417 7 месяцев назад

    @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}

  • @Vaishnav-zk2tf
    @Vaishnav-zk2tf Год назад +2

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

  • @abdulwadoodh5757
    @abdulwadoodh5757 Год назад

    How did you replace nums to studs?

  • @nazeebahmed1050
    @nazeebahmed1050 9 месяцев назад

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

    • @audiomac
      @audiomac 5 месяцев назад

      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!

  • @user-fm9sm6ho1u
    @user-fm9sm6ho1u 11 месяцев назад

    Nuvu king mava🤗

  • @abhijeetkulkarni8246
    @abhijeetkulkarni8246 Год назад

    Sir please try to make videos with white screen

  • @-GANGUPALLIMAHAMMED
    @-GANGUPALLIMAHAMMED 9 месяцев назад

    Comparator is an interface so how object will created??

  • @inspiredomkar1239
    @inspiredomkar1239 10 месяцев назад +1

    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);
    }
    }

  • @shraddhashetty8659
    @shraddhashetty8659 9 месяцев назад +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);

    }

    }

  • @sumantagorai5880
    @sumantagorai5880 8 месяцев назад

    1 for swap &
    -1 for no swap

  • @gurrammahenderreddy4586
    @gurrammahenderreddy4586 Год назад +3

    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);
    }
    }

  • @sudeepbansal5234
    @sudeepbansal5234 Год назад

    You are awesome 👏👏👏

  • @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 😊

  • @mirhaidar632
    @mirhaidar632 Год назад

    what is the IDE he is using?

  • @gyanendramaurya1796
    @gyanendramaurya1796 4 месяца назад

    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

  • @rahuljmd
    @rahuljmd Месяц назад

    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....

  • @kashishswami3268
    @kashishswami3268 7 месяцев назад

    14:03

  • @abhishekkumargupta9548
    @abhishekkumargupta9548 Год назад

    opiest explaination

  • @yashjoshi5709
    @yashjoshi5709 Год назад

    aaj mai alien banne vaala tha sir but aaj bhi merko aadhi cheeze samajh nahi aayi

  • @akshaysilgari2097
    @akshaysilgari2097 7 месяцев назад

    Got lamda expression clear from u.

  • @maleeshasandakalum6213
    @maleeshasandakalum6213 11 месяцев назад

    ❤❤❤❤❤❤❤❤

  • @actandrepeat
    @actandrepeat Год назад

    What if two students have the same age?

  • @sayantanhalder1056
    @sayantanhalder1056 13 дней назад +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

  • @ooogabooga5111
    @ooogabooga5111 2 месяца назад

    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.

  • @hiibuddy
    @hiibuddy 8 месяцев назад

    Ohh bhupendra jogi 😂😂😂

  • @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 10 месяцев назад +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 10 месяцев назад +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 10 месяцев назад

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

    • @sharabugnanesh3098
      @sharabugnanesh3098 10 месяцев назад +1

      @@codework2434 yes I need to mention at left

    • @codework2434
      @codework2434 10 месяцев назад +1

      @@sharabugnanesh3098 Thanks about the "official java update"

  • @priyanshukhullar-tc7ss
    @priyanshukhullar-tc7ss 9 месяцев назад +1

    Thankyou Reddy Ji lots of love.

  • @Manjot_singh2002
    @Manjot_singh2002 5 месяцев назад

    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);
    }
    }

  • @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);


    }

  • @dominicdumenil861
    @dominicdumenil861 6 месяцев назад

    import java.util.List;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    public class Student {
    public static void main(String[] args) {
    Comparator com = ( i, j) -> s1.length()>s2.length()? 1 : -1;
    List names = new ArrayList();
    names.add("Nathan");
    names.add("Dominic");
    names.add("Nikita");
    names.add("Sharon");
    names.add("Jessica");
    Collections.sort(names, com);
    System.out.println(names);
    }
    }

  • @ROSHAN-HARI-BALAJE
    @ROSHAN-HARI-BALAJE Месяц назад

    Ternary Operator ❌ Tatari Operator ✔

  • @abukhandaker7558
    @abukhandaker7558 5 месяцев назад

    Too greedy with the ads

  • @Shri577
    @Shri577 7 дней назад

    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()

  • @rohitkulkarni1261
    @rohitkulkarni1261 25 дней назад

    Fucking awesome❤

  • @rahuljmd
    @rahuljmd Месяц назад

    Homework:
    import java.util.*;
    class Solution {
    public static void main(String[] args) {
    // Write your code here
    Comparator com=new Comparator(){
    //jai mata di : Anonymous Inner class
    public int compare(String s1, String s2){
    if(s1.length()>s2.length()){
    return 1;
    }
    else return -1;
    }
    };

    List al=new ArrayList();
    al.add("Rahul");
    al.add("DK");
    al.add("J");
    Collections.sort(al,com);
    System.out.println(al);
    }
    }

  • @shazirnazir3501
    @shazirnazir3501 8 месяцев назад

    public class SortNamesByLength {
    public static void main(String[] args) {
    List names = new ArrayList();
    names.add("Rashid Khan");
    names.add("Rohit Sharma");
    names.add("Babar Azam");
    names.add("David Warner");
    names.sort(Comparator.comparingInt(String::length));
    for (String name : names) {
    System.out.println(name);
    }
    }
    }

  • @ShubhamMishra-lo6wz
    @ShubhamMishra-lo6wz 4 месяца назад

    package org.example.Strings;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    public class SortWithLength {
    public static void main(String[] args) {
    Comparator cp = new Comparator() {
    public int compare(String i, String j) {
    char[] ch = i.toCharArray();
    char[] ch2 = j.toCharArray();
    if(ch.length

  • @krushnapatil9196
    @krushnapatil9196 Год назад

    w

  • @gautamkumarpandey9494
    @gautamkumarpandey9494 Год назад +4

    // Sort the list of strings on the basis of length of string.
    List list = new ArrayList();
    list.add("Navin Reddy sir");
    list.add("Harendra Pandey jee");
    list.add("Gautam");
    list.add("Nitesh");
    Comparator com = new Comparator() {
    @Override
    public int compare(String o1, String o2) {
    if(o1.length()>o2.length())return 1;
    else return -1;
    }
    };
    System.out.println("List before sorting");
    System.out.println(list);
    System.out.println("List after sorting");
    Collections.sort(list,com);
    System.out.println(list);