Comparable and Comparator Implementation in Java with Example [Interview Question]
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
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
Many congratulations Vrushab 👏👏👏👏. Keep learning keep shining Man 👍👍
Awesome ! Keep up the good work
Best channel to prepare for java interviews.
Thanks a lot Saurabh 🙂👍
detailed and clear explaination of concepts !!
Thanks
Amazing video and nicely explained. Thank you.
Thanks Rohit 👍🙃
I now binge watch your videos even while eating, thanks for such amazing content !
Thanks Gyan 🙂👍. Hope you reach to your dream job 👍👍keep learning keep rocking 🎸🎶🎶🎸🎶🎶
Every topic is explained very well.Thanks a lot
You're welcome
beautifully explained, such a simple understanding of complex topics.
M glad it's helpful.
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?
you are very good with your explanation with example
Thanks...
Great Content!! Thanks!
Thanks Priyanka 🙂👍
Excellent videos by you
Thanks Sai 🙂👍
Opened to learn this topic....and after completing the video i remember only ur voice...🥰
Thanks 🙂🙂
Thank you, this was helpful
Thanks Kritika 👍👍
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()))
perfect
Can use comparator without implementation of comparable interface?
Thanks alot ..good explanation ..
You are welcome
very nice and excellent tutotial
Thanks
One small suggestion. If you are using java8 or above version then you can optimize your code by lambda expression.
czcams.com/play/PLyHJZXNdCXsdeusn4OM33415DCMQ6sUKy.html
You have a such a cute voice 😍😍
Thank you for making it easy to learn these concept.
You're welcome Zabhash
well explained!!
Thanks ❤️👍
Exellent :)
Thanks
Thank you sister 🌿🌿🌿
Our pleasure Krishnavamsi🙂🙂👍👍
1:50 - can you please explain what is the exact value that is expected in this.id and o.id ?
Me bhi yahi dhundh raha hu but koi bhi apni video isse explain nahi kar raha
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
Thank you
🙂👍
nice explanation mam, I have a query I tried using by name and by address it is not working can u help with that?
Can you please elaborate your issue so that I can help you out
can u please explain elaborately regarding with better examples, this looks like it went fast forward
The way u say java error thrown at our faces I feel it actually 😂
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
Looking for the same
In ascending order
When we are calling the sort method which is static by passing the parameter.I think the logic is implemented inside this method
great videos. Are you gujarati?
Yes I am 😊🤓. Though I am an Indian too. How did u catch that though? M curious to know that 🙃
Mam can we use collection.sort( ) instead of array.sort( )?
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()
@@CodeDecode Is it ok to use Arrays.sort() method for List object. if not , which one is better to use in this case ?
Companies want to see implementation of these comparator and comparable interfaces through lambda express.
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
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
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!
Nice question Abhijit we will put video on this 👍🙂
@@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()));
});
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]
Same question i have
bro, in Employee class, we missed to add toString() method, that's why.
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
use compareToIgnoreCase mathod and return in compareTo method.
userName.compareToIgnoreCase(user.userName);
public int compareTo(User user) {
return userName.compareToIgnoreCase(user.userName);
}
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..
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);
}
}
Comparator nahi samjha
No worries. Where you missed ? Not able to understand anonymous class ?
Can I get ur mail
It's codedecodebusiness@gmail.com