Reputation: 524
The List which contains data is in an order of
List<String> list = new ArrayList<String>();
list.add('R');
list.add('L');
list.add('H');
list.add('A');
If I have to display the list in an order of L,H,R,A.
I tried to add each list value in a LinkedHashMap and and added all in another Linked Hashmap according to the requirement.
Is there any other best way that I can sort this.
Upvotes: 0
Views: 74
Reputation: 1768
You can use java.util.Collections.sort method, pass the array and a comparator:
Collections.sort(list,new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
// write your code to decide the order, return negative value for element that you want to appear before another element, zero for equality. same at compareTo works.
}
});
So, if you would like to sort only the LRHA letters, you can do the following (and i assume that any other string will be placed in the end)
List<String> list = new ArrayList<String>();
list.add('R');
list.add('L');
list.add('H');
list.add('A');
Collections.sort(list,new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
if(s1 == null)
return 2;
if(s2 == null)
return -2;
if(s1.equals("L")) return -1;
if(s2.equals("L")) return 1;
if(s1.equals("H")) return -1;
if(s2.equals("H")) return 1;
if(s1.equals("R")) return -1;
if(s2.equals("R")) return 1;
if(s1.equals("A")) return -1;
if(s2.equals("A")) return 1;
return 2;
}
});
Upvotes: 1