Reputation: 91
I want sort the List by values in the list , it contains three values , first value is integer i convert that into string and other two values are string in nature, i want to sort the list by first string .
List<List<String>> detail_View = new ArrayList<List<String>>();
List<String> fieldValues =fieldValues = new ArrayList<String>();
String aString = Integer.toString(ScreenId);
fieldValues.add(aString);
fieldValues.add(DisplayScreenName);
fieldValues.add(TableDisplay);
detail_View.add(fieldValues);
In above code i have to sort list values by ScreenId
Upvotes: 5
Views: 10782
Reputation: 10812
Java 8 version:
Collections.sort(fieldValues, Comparator.comparing(e -> e.get(0)));
This version will sort the integers as numbers, not as strings:
Collections.sort(fieldValues, Comparator.comparing(e -> Integer.valueOf(e.get(0))));
Upvotes: 1
Reputation: 6890
You have to use two concept:
Collections.sort
utility.Comparator<T>
interface.I write your solved problem following:
First you have to write your comparator:
class CustomComparator implements Comparator<List<String>>
{
@Override
public int compare(List<String> o1,
List<String> o2)
{
String firstString_o1 = o1.get(0);
String firstString_o2 = o2.get(0);
return firstString_o1.compareTo(firstString_o2);
}
}
then you using Collections utility as following:
Collections.sort(detail_View, new CustomComparator());
after these step, your list:
List<List<String>> detail_View = new ArrayList<List<String>>();
will sorted by first index of any nested list.
For more information related to this concept see:
Upvotes: 4
Reputation: 198023
Make a class with the three fields; don't move them around as a List<String>
, that's just silly. Making that class comparable will let you sort them as you like.
Upvotes: 2
Reputation: 262474
Supposing that you do not want to sort the integer (stored as a String) alphabetically, you cannot use the default comparator, but have to convert it back to an integer first:
Collections.sort(detail_view, new Comparator<List<String>>(){
int compareTo(List<String> a, List<String> b){
return Integer.valueOf(a.get(0)).compareTo(Integer.valueOf(b.get(0));
}
});
May I suggest not using a List for the three pieces of data, but your own bean class?
Upvotes: 3