Sorting ArrayList of Arraylist<String> in java

38,168

Solution 1

Assuming your Lists in your List has Strings in the order id, name, address and number (i.e. name is at index 1), you can use a Comparator, as follows:

List<List<String>> list;
Collections.sort(list, new Comparator<List<String>> () {
    @Override
    public int compare(List<String> a, List<String> b) {
        return a.get(1).compareTo(b.get(1));
    }
});

Incidentally, it matters not that you are using ArrayList: It is good programming practice to declare variables using the abstract type, i.e. List (as I have in this code).

Solution 2

I feel bad posting this, because List<Contact> would be the much better choice. Something like this would be possible, though:

ArrayList<ArrayList<String>> yourList = ...
Collections.sort(yourList, new Comparator<ArrayList<String>>() {
    @Override
    public int compare(ArrayList<String> one, ArrayList<String> two) {
        return one.get(1).compareTo(two.get(1));
    }
});

Solution 3

  import java.util.Collections;
  import java.util.Comparator;
  import java.util.List;


  public class ListsUtils {

      public static void sortListOfLists(List < List < String >> listOfLists) {

          // first sort the inner arrays using collections.sort
          for (List < String > innerList: listOfLists) {
              Collections.sort(innerList);
          }

          // now sort by comparing the first string of each inner list using a comparator
          Collections.sort(listOfLists, new ListOfStringsComparator());
      }

      static final class ListOfStringsComparator implements Comparator < List < String >> {

          @
          Override
          public int compare(List < String > o1, List < String > o2) {
              // do other error checks here as well... such as null. outofbounds, etc
              return o1.get(0).compareTo(o2.get(0));
          }

      }
  }

I guess I just assumed you had to sort a list of string arrays... thats why I sorted the list of inner arrays first, then sorted the outer list by comparing the 1st item of each array. Didnt read the contacts you had in your answer.

In that case remove the for loop for sorting the inner list and you should still be able to sort using the comparator, but compare to the right index instead of the 1st element.

Collections.sort(listOfLists, new ListOfStringListComparator());

Solution 4

Comparator / Comparable Interfaces can't help because I don't have any objects.

Incorrect. You do have objects. All of the things you are trying to sort are objects.

If you are trying to sort the ArrayList<String> objects in an ArrayList<ArrayList<String>>, you need to implement a Comparator<ArrayList<String>>. (The Comparable approach is the wrong one for this data structure. You would need to declare a custom subclass of ArrayList ... and that's yuck!)


But a better idea would be to represent your objects with custom classes. In this case, your ArrayList of String should be a custom Contact class with 4 fields, getters and (if required) setters. Then you declare that as implementing Comparable<Contact>, and implement the compareTo method.


Other Answers show how to implement a Comparator based on just one field of the list. That may be sufficient, but it will give you a sort order where the order of a pair of different "John Smith"s would be indeterminate. (I would use a second field as a tie-breaker. The Id field would be ideal if the ids are unique.)

Solution 5

You should create a class for your data structure (if you can't, then specify why. I can't see any good reason not to):

public class Contact implements Comparable {
    private String id;
    private String name;
    private String address;
    private String number;

    // Getters and setters, and compareTo.
}

Then use that in your list instead:

List<Contact> contacts = new ArrayList<Contacts>();

Sorting it will then be trivial.

Share:
38,168
Nikhil Agrawal
Author by

Nikhil Agrawal

Experienced and Passionate Java developer with a wide range of skill set and wide technology background in both core and advanced java world. I have experience of working with agile methodologies with hands on experience of tools like JIRA and confluence. I have had training and am following secure software development methods. I have been using Secure SDLC in my projects for quite a while. I have handled the requirements from initiation to deployment phase, like requirement gathering and analysis, transforming business requirement into technical requirement, preparing technical designs, developing and testing the module with the help of a development team and deployment. I like to explore and implement new technologies and have implemented new technologies in projects before. I like to read technical news, articles and blogs to keep myself updated. Technology Stack : • Java • Spring Framework • SpringBoot • Microservices • Hibernate • REST Web Services • Javascript, jQuery, HTML • Backbone.js, Marionette.js • Git • JIRA • Salesforce • Jenkins

Updated on July 05, 2022

Comments

  • Nikhil Agrawal
    Nikhil Agrawal almost 2 years

    I have an ArrayList of ArrayList of String.

    In Outer ArrayList on each index each Inner ArrayList has four items have four parameters.

    1. Contacts Id
    2. Contacts Name
    3. Contacts Adress
    4. Contacts Number

    Now I want to sort the complete ArrayList of the on the basis of Contact Name Parameter.

    Means I want to access the outer Arraylist and the inner ArrayList present on each index of outer Arraylist should be sorted according to contact Name.

    Comparator / Comparable Interfaces not likely to help me.

    Collection.sort can't help me

    Sorting Arraylist of Arraylist of Bean. I have read this post but it is for ArrayList of ArrayList<Object>. How to figure out this problem?