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
Collections class sort() method is used to sort a list in Java. We can sort a list in natural ordering where the list elements must implement Comparable interface. We can also pass a Comparator implementation to define the sorting rules.
Using the toCharArray() method Get the required string. Convert the given string to a character array using the toCharArray() method. Sort the obtained array using the sort() method of the Arrays class. Convert the sorted array to String by passing it to the constructor of the String array.
To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections. sort() method like below.
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:
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With