Reputation: 347
How do I create a Comparator that compare the string
and display the integer
in reverse order leaving the character at same position. eg input=10,20,100,a,50
output
should be 100,50,20,a,10
.
class StringLengthComparator implements Comparator<String>{
@Override
public int compare(String o1, String o2)
{
return -o1.compareTo(o2);
}
Upvotes: 0
Views: 226
Reputation: 443
You can't define Comparator for a string comparison to Integer because we can not compare alphabet with integer value.
so when you use Comaprator or Collection.sort(list<>) will always sort Integer and sort character string.
List<String> numAlpha=new ArrayList<String>();
numAlpha.add("2");
numAlpha.add("8");
numAlpha.add("7");
numAlpha.add("b");
numAlpha.add("6");
numAlpha.add("y");
numAlpha.add("test");
numAlpha.add("alpha");
Collections.sort(numAlpha);
System.out.println(numAlpha.toString());
output: [2, 6, 7, 8, alpha, b, test, y]
Upvotes: 0
Reputation: 393811
There is no way to define a Comparator
that would produce the output you want, since a Comparator
must define a consistent ordering, and your requirements don't.
Consider these two inputs :
10,20,100,a,50
10,20,100,a,5
In the first, you want the order to be :
100,50,20,a,10
While in the second you want :
100,20,10,a,5
You can't define a Comparator
in which for some inputs "a">"10" while for others "a"<"10".
Upvotes: 2