#95 Comparator vs Comparable in Java

preview_player
Показать описание
Check out our courses:

Coupon: TELUSKO10 (10% Discount)

Coupon: TELUSKO20 (20% Discount)

For More Queries WhatsApp or Call on : +919008963671

Udemy Courses:

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

More Learning :

Donation:
PayPal Id : navinreddy20
Рекомендации по теме
Комментарии
Автор

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

naulk
Автор

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

Noah-zcmv
Автор

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

suhailsharieff
Автор

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

Democracy_Manifest
Автор

The last 2 mins are very insightful!! 😍😍

varsheethtv
Автор

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.

AmeyChittar
Автор

best java instructor i’ve ever come across

rhea
Автор

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

tarekabushaheen
Автор

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

dypsking
Автор

Sorting the String based on the length:

public class PractComparator {

public static void main(String[] arg) {
Comparator<String> com = new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
};

List<String> fruit = new ArrayList<>();
fruit.add("Banana");
fruit.add("Mandarin");
fruit.add("PineApple");
fruit.add("Apple");

Collections.sort(fruit, com);

System.out.println(fruit);

}

}

shraddhashetty
Автор

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

moviecraze
Автор

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

karanraut
Автор

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

vikrantsingh
Автор

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

pratikkumarsingh
Автор

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?

shriharis.s
Автор

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

xacademia
Автор

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

Sumanth_Siddareddy
Автор

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

beinghuman
Автор

Love your videos, learn new thing every time.

adityarao
Автор

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

gyanendramaurya