I have a list with values
I want the list to be sorted out as first letter ascending and last letter descending so the sorted list is
How can i do it in java ? Plz help.
Not tested it, something like this, should work.
Collections.sort(list, new Comparator<String>() {
public int compare(String e1, String e2) {
int c = new Character(e1.chartAt(0)).compareTo( e2.charAt(0) );
if( c!=0 )
return c;
return new Character(e2.chartAt(e2.length()-1)).compareTo( e1.charAt(e1.length()-1) )
}
});
You could use Collections.sort()
and then specify the Comparator
where ascending or descending.
List<String> list = new ArrayList<String>();
Collections.sort(list, new Comparator<Item>() {
@Override
public int compare(String s1, String o2) {
return s1.compareTo(s2);
}
});
It might look like this.
public FirstLetterComparator implements Comparator<String>{
public int compare(String left, String right){
String leftFirst = left.substring(0,1);
String rightFirst = right.substring(0,1);
return left.compareTo(rightFirst) && ;
}
}
public LastLetterComparator implements Comparator<String>{
String leftLast = left.substring(left.length-2,left.length-1);
String rightLast = right.substring(right.length-2,right.length-1);
return leftLast.compareTo(rightLast);
}
List<String> yourList = new ArrayList<String>();
Collections.sort(yourList,new FirstLetterComparator());
Collections.sort(yourList,Collections.reverseOrder(new LastLetterComparator()));
There are two different comparators to make it consistent you have to think about one that will be acceptable for your criteria.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.