Тёмный

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

Подписаться
Просмотров 114 тыс.
% 742

java9s.com
Example code : github.com/java9s/tutorials/tree/master/java/JavaCollections
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:
ru-vid.com/group/PLkiVxfkxAYd1Typb8x-2nbzgsxdMQesKg
Multithreading in Java tutorial:
ru-vid.com/group/PLkiVxfkxAYd1i9eX9X74eoTjKZXzvITMX
Spring 3 MVC Framework tutorials:
ru-vid.com/group/PLA3AD4211EBE70E86
Spring Framework Tutorials:
ru-vid.com/group/PL2882729612B70122
Design Patterns in Java:
ru-vid.com/group/PLkiVxfkxAYd1xWYj9aOWoTevqok0VoYe7
ru-vid.com/group/PLkiVxfkxAYd2TAn--1BH1ERvYbHxh11Qs
Complete Generics Tutorials playlist
Collections in Java
ru-vid.com/group/PLkiVxfkxAYd1aPKf45Byl24NqSNgHGbOf

Опубликовано:

 

11 апр 2016

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 35   
@baluadaka156
@baluadaka156 8 лет назад
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
@amritasingh1105
@amritasingh1105 7 лет назад
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 ??
@LetsBeHuman
@LetsBeHuman 5 лет назад
11:12 - What is the point of using Iterator when we can just use Enhanced For loop.
@mrunalv9972
@mrunalv9972 7 лет назад
Comparable doesnt belong to the collection interface , it belongs to java.lang package
@michawojcik1519
@michawojcik1519 8 лет назад
Another great explanation. Thank you for your videos.
@nikhiler5691
@nikhiler5691 4 года назад
Thank you sir, This video was really helpful to me .
@subramanianchenniappan4059
@subramanianchenniappan4059 3 года назад
Thanks bro. Useful for interview
@abhisekcrazy
@abhisekcrazy 7 лет назад
Sir Comparable not belongs to collection interface, it belongs to java.lang package.
@IqbalHamid
@IqbalHamid 6 лет назад
There are two components in java, both sharing the same name: There is the Collections interface which Lists and sets descend from. In additions to this, there is a Collections class which provides static methods for sorting. I wonder if y ou may be confusing the two?
@anonymousviper4778
@anonymousviper4778 7 лет назад
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 :)
@beawlp
@beawlp 7 лет назад
Natural ordering when we use Comparable applied for Wrapper objects (Integer, Long, etc) and String. If we are trying to sort objects other than those objects, we need to provide the sorting logic in compareTo method as like as in Comparator's compare.
@SatyabrataPaital
@SatyabrataPaital 7 лет назад
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.
@PankajKumar-qk8oh
@PankajKumar-qk8oh 4 года назад
Nice explanation
@TheHobee
@TheHobee 4 года назад
Thank you for the help!
@briensmarandache
@briensmarandache 6 лет назад
is this equally valid within compareTo()... return this.getPrice() - o.getPrice() . .......?
@olfamoussaoui
@olfamoussaoui 8 лет назад
Thank you for this video :)
@anilpal8333
@anilpal8333 4 года назад
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
@leonelramos4335
@leonelramos4335 8 лет назад
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;
@jvsnyc
@jvsnyc 4 года назад
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.
@suryadk1792
@suryadk1792 7 лет назад
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 int()(Math.random()*100)+1.But in output we have not seen any number which is greater than 100. any one can explain this
@danieljonnakuti
@danieljonnakuti 6 лет назад
Math.random() returns a number between 0(inclusive) and 1(exclusive). So the number will not be greater than 100.
@ludvigwesterdahl2086
@ludvigwesterdahl2086 7 лет назад
Wouldnt it be legal to simply one-line the compareTo Method? return this.getPrice() - o.getPrice(); ?
@rathorelaxmirathore
@rathorelaxmirathore 7 лет назад
Ludvig Westerdahl ,if u want to simply in one line , below will be more appropriate return this.price.compareTo(object.price)
@jayatheerthakv
@jayatheerthakv 7 лет назад
CompareTo method accepts object as an argument, it will not work for primitive types
@mohaababudevalla918
@mohaababudevalla918 8 лет назад
good explanation
@TheGuroguro12
@TheGuroguro12 7 лет назад
Thank you very much.
@suryadk1792
@suryadk1792 7 лет назад
good one...
@suman6327
@suman6327 7 лет назад
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.
@leonelramos4335
@leonelramos4335 8 лет назад
thank you, i know understand this.
@Stonecoldsteverock
@Stonecoldsteverock 8 лет назад
Whats the answer to the second brain teaser?
@manish6992
@manish6992 6 лет назад
coz list require methods to sort unlike hashset which can be sorted by using tree set
@devrajatverma
@devrajatverma 7 лет назад
Answer to Second Brain Teaser: Set already have sorted implementation "TreeSet" and similarly Map too have "TreeMap" which sort the elements as the added.
@arafatnoor
@arafatnoor 7 лет назад
Thanks
@rollinOnCode
@rollinOnCode 3 года назад
why do you sound so depressed?