How to sort 2D ArrayList <String> only by the first element
To avoid duplicate statements , I looked through this article and this is not quite what I wanted.
Every other two-dimensional ArrayList question involved numbers doubleor int; my question is about Strings.
What am I doing
I have a 2D ArrayList defined as follows:
ArrayList<ArrayList<String>> namesAndNumbers = new ArrayList<ArrayList<String>>();
The idea is that the first element in each row of ArrayLists contains the names, and the remaining columns in each row contain phone numbers (unknown amount). Therefore, I would like to avoid converting it to a regular array.
Example
Say I populated my ArrayList and I have this:
{"Mike", "(805) 766-4920"}
{"Emily", "(705) 668-9292", "(705) 555-1060"}
{"James", "(605) 965-2000"}
I expect my output to be as follows:
{"Emily", "(705) 668-9292", "(705) 555-1060"}
{"James", "(605) 965-2000"}
{"Mike", "(805) 766-4920"}
, , .
, , - 2D ArrayList . , . .
Collections.sort Comparator, , :
List<ArrayList<String>> namesAndNumbers = new ArrayList<ArrayList<String>>();
namesAndNumbers.add(new ArrayList<String>(Arrays.asList("Mike", "(805) 766-4920")));
namesAndNumbers.add(new ArrayList<String>(Arrays.asList("Emily", "(705) 668-9292", "(705) 555-1060")));
namesAndNumbers.add(new ArrayList<String>(Arrays.asList("James", "(605) 965-2000")));
Collections.sort(namesAndNumbers, new Comparator<ArrayList<String>>() {
@Override
public int compare(ArrayList<String> o1, ArrayList<String> o2) {
return o1.get(0).compareTo(o2.get(0));
}
});
System.out.println(namesAndNumbers);
:
[[Emily, (705) 668-9292, (705) 555-1060], [James, (605) 965-2000], [Mike, (805) 766-4920]]
:
final Comparator<List<String>> comparator = new Comparator<List<String>>() {
public int compare(List<String> pList1, List<String> pList2) {
return pList1.get(0).compareTo(pList2.get(0));
}
};
final List<List<String>> lists = Arrays.asList(
Arrays.asList("Mike", "(805) 766-4920"),
Arrays.asList("Emily", "(705) 668-9292", "(705) 555-1060"),
Arrays.asList("James", "(605) 965-2000")
);
Collections.sort(lists, comparator);
for (List<String> list : lists) System.out.println(list);
For a change. Why don't you use HashMap if you don't want to duplicate keys. the key will be a name and the value will be an ArrayList of numbers
String name="John";
ArrayList<String> phonenumbers=new ArrayList<String>();
phonenumbers.add("80925887");
phonenumbers.add("+166476654");
TreeMap<String, ArrayList> tm=new TreeMap<String, ArrayList>();
tm.put(name, phonenumbers);