Sorting collections in java | Comparable & Comparator in java | Java9s.com

preview_player
Показать описание
To sort the elements, we should be able to compare the element with another element and only then we can judge which one should go first and which in the next position.

Java collections framework has an interface called Comparable which has a method called compareTo method.

CompareTo method is where the criteria is declared and this is called natural ordering for that kind of objects

So, How does compareTo method decides which object is less than, equal or greater than an object?

compareTo method accepts an object of same instance type and based on certain criteria defined, it returns an integer which indicates if an object is less or greater or equal in ordering.
This Collections class defines two methods called Sort and Sort a list with a comparator.

These two methods accept a List as a collection and orders all the elements based on certain criteria.

Now, if you observe the signature of the sort method, you can see that it is static and it only accepts the collection with elements which has implemented the comparable interface.

This is because, without implementing Comparable, the will be no compareTo which defines the natural ordering of elements.

You can see that this documentation clearly states that it uses natural ordering which means that it relies on compareTo method.
Collections framework has an interface called Comparator which defines compare method.

It accepts two objects of a type and compares both on certain criteria and then returns an integer.

Similar to compareTo method, this method also returns a -ve integer or +ve integer or zero.

If a negative integer is returned, first argument is less or comes after the second object.

If a positive integer is returned, first argument is comes first and second one always after the first one.

If zero, then both stand at the same level in ordering.

Complete Java Beginners Tutorials:

Multithreading in Java tutorial:

Spring 3 MVC Framework tutorials:

Spring Framework Tutorials:

Design Patterns in Java:

Complete Generics Tutorials playlist

Collections in Java
Рекомендации по теме
Комментарии
Автор

collections.sort() method is only applicable for List not set why because by default set having a sorting order i, e TreeSet .so incase of sorting the objects in set.then we can use the TreeSet

baluadaka
Автор

Another great explanation. Thank you for your videos.

michawojcik
Автор

11:12 - What is the point of using Iterator when we can just use Enhanced For loop.

LetsBeHuman
Автор

Comparable doesnt belong to the collection interface, it belongs to java.lang package

mrunalv
Автор

I have one doubt sir... if we see @2:21, were you are talking that, when object 1(i.e this object) is less than the object we're comparing with i.e object2, we get a -ve value. Then according to the concept, if object 1< object2, then obviously object 1 should come before object 2 while printing, as it is smaller, hence has returned a -ve value, but your videos shows reverse of that, i.e you're saying object 2 will come before object1. Can you please please explain ??

amritasingh
Автор

Thank you sir, This video was really helpful to me
.

nikhiler
Автор

Sir Comparable not belongs to collection interface, it belongs to java.lang package.

abhisekcrazy
Автор

Answer for Second BrainTeaser : Most (but not all) Set implementations do not have a concept of order, so Collections.sort does not support them as a whole.

suman
Автор

Can you sow it as sorting like there is empId, empName, EmpPhone, EmpAddr for multiple Employee But we have to sort it Using only EmployeeId.and how to show it.

SatyabrataPaital
Автор

can anyone pls explain me..in above ex, sir created own way to sort in comparator ...but sir also created own login in comparable(inside CompareTo method of comparable)..then if comparable uses natural ordering..why was it necessary to write some logic inside compareTo method?..please any1 explain this 2 me, thanks in advance :)

anonymousviper
Автор

Answer to Second Brain Teaser: Set already have sorted implementation "TreeSet" and similarly Map too have "TreeMap" which sort the elements as the added.

devrajatverma
Автор

I appreciate your work and will watch more videos, BUT --
as
Amrita Singh kindly pointed out, you had the "polarity" or direction wrong where you explain both .compareTo( o2 ) instance method and Compare( o1, o2 ) static method. Well, she mentioned .compareTo( o2 ) -- you say that .compare( o1, o2 ) works similarly, which it does, but then you repeat the mistake on which way the difference goes. If the number is negative, then the SECOND object is larger than the FIRST one, so sorting in ascending order, we have FIRST then SECOND.

If the number is positive, then the SECOND object is smaller than the FIRST one so they will come SECOND then FIRST in ascending order.

What you showed would be accurate if we were attempting to sort in descending order.

jvsnyc
Автор

is this equally valid within compareTo()... return this.getPrice() - o.getPrice() .

briensmarandache
Автор

in above example, the taken class name is car and have some set()methods in it those it is ok.but when setting the value like in output we have not seen any number which is greater than 100. any one can explain this

suryadk
Автор

for the brain teaser would your compareTo or compare method do something like this

if(car.getPrice()%2==0){
return 1;
}else if(car.getPrice%2 != 0){
return -1;
}
return 0;

leonelramos
Автор

Whats the answer to the second brain teaser?

Stonecoldsteverock
Автор

Wouldnt it be legal to simply one-line the compareTo Method?
return this.getPrice() - o.getPrice();
?

ludvigwesterdahl
Автор

I have one question can we remove duplicate element and sort them using Collections.sort() or some other way if our data structure is list
similar like TreeSet do it used hascode and equals remove duplicate and for sorting it used compareTo or compare

my question is that if we have list of object if we want to sort them we can use Collections.sort() but if we want to remove duplicate can we do this or it is impossible

anilpal