Comparable:
java.lang
|
Comparator:
java.util
|
1) It
provides single sorting sequence.
We
can sort on particular single scenario.
|
It
provides multiple sorting sequences.
We
can provide different comparator to sort.
|
2) Comparable
affects the original class i.e. actual class is modified.
|
Comparator
doesn't affect the original class i.e. actual class is not modified.
|
3)
Comparable provides compareTo()
method to sort elements.
|
Comparator
provides compare() method to sort
elements.
|
4)
We can sort the list elements of Comparable type by Collections.sort(List) method.
|
We
can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.
|
package com.comparator;
import java.util.Comparator;
public class StringComparator implements Comparator<String>{
@Override
public int compare(String objStr1, String objStr2)
{
int result
= 0;
if(objStr1!=null && objStr2!=null) {
result = -1 * objStr1.compareTo(objStr2);
}
return result;
}
}
package com.comparator;
import java.util.Map;
import java.util.TreeMap;
public class TestComparator {
public static void main(String[] args) {
/**
* Default Sorting accoding to comparable implemetation of
* string class in ascending order.
*/
Map<String,String> map = new TreeMap<String,String>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "3");
System.out.println(map);
/**
* Using external comparator sort String keys in descending order.
*/
StringComparator comparator = new StringComparator();
Map<String,String> compMap = new TreeMap<String,String>(comparator);
compMap.put("A", "1");
compMap.put("B", "2");
compMap.put("C", "3");
System.out.println(compMap);
}
}
Output:
{A=1, B=2, C=3}
{C=3, B=2, A=1}
No comments:
Post a Comment