To avoid the duplicate claims, I've looked at this post and it isn't exactly what I wanted.
Every other 2D ArrayList question involved double
or int
numbers; my question is about Strings
.
I have a 2D ArrayList, defined like this:
ArrayList<ArrayList<String>> namesAndNumbers = new ArrayList<ArrayList<String>>();
The idea is that the first item in every row of ArrayLists contains the names, and the rest of the columns in each row contains the phone numbers (unknown amount). Therefore I would like to avoid converting it to a regular array.
Let's say I've 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 this:
{"Emily", "(705) 668-9292", "(705) 555-1060"}
{"James", "(605) 965-2000"}
{"Mike", "(805) 766-4920"}
I want to keep the numbers corresponding with the names, but simply sort the array by the name.
I'm hoping for a built-in function manipulation type of thing, but I'd be fine if someone created a sorting array method for me with an 2D ArrayList as the input. I haven't seen any question that answers this issue explicitly. I will continue trying to come up with an answer myself as well.
You can use Collections.sort
and provide a custom Comparator
where you compare the first element of each list, i.e the name :
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);
Output :
[[Emily, (705) 668-9292, (705) 555-1060], [James, (605) 965-2000], [Mike, (805) 766-4920]]
Create a custom comparator:
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);
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