Hi swapna,
Please
UseCodeTags for inserting any code in your post.
here the sort method will let sort the collection(list in your case) according to the comparator.if you would not give it the comparator argument then the sort will be performed according to the natural ordering(accordingly with the comparable implementation means the natural ordering is determined as comparable compareTo method so the elements in the comparable must implement comparable interface for determining natural ordering).but sometimes we can face a situation when we do not want to sort the collection as per natural ordering but on some another basis.here the interface Comparator help us,we can define a strategy for comparing the instances by overriding its Compare method.
In your code new Comparator() {@Override...} is a anonymous class(it does not have name) which is implementing the Comparator interface and inside its class body it is overriding the interface Compare method.
here is the example:
you can see the difference at line 25 and 32.at line 25 the sort is performed according to the employee id(natural ordering,here it uses a comparable compareTo method) and at line 32 the sort is performed according to the length of the employee name(here the Comparator compare() method is used to find the ordering criteria).
Hope it helps!
kind regards,
Praveen