Java: How do I sort multiple ArrayList by their size?

后端 未结 2 863
北荒
北荒 2021-02-07 21:45

I have 9 different ArrayList and I want to have a list of the top 5.

I\'m thinking of sorting those ArrayLists by their sizes.

Is it

相关标签:
2条回答
  • 2021-02-07 22:02

    you can do like this as well

    public static <T> List<List<T>> sort(List<List<T>> list) {
            list.sort((xs1, xs2) -> xs1.size() - xs2.size());
            return list;
        }
    
    0 讨论(0)
  • 2021-02-07 22:16

    What you could do is the following:

    // this List of lists will need to contain 
    // all of the ArrayLists you would like to sort
    List<ArrayList> allTheLists; 
    Collections.sort(allTheLists, new Comparator<ArrayList>(){
        public int compare(ArrayList a1, ArrayList a2) {
            return a2.size() - a1.size(); // assumes you want biggest to smallest
        }
    });
    

    This will sort the list of lists by the length of each list. The first element in the sorted list will be the longest list, and the last one will be the shortest list.

    Then, you can iterate through the first 5 lists to see what the top 5 were.

    Some links for reference:

    • Sorting tutorial
    • Collections Javadoc
    • Comparator Javadoc

    Depending on how you have your ArrayLists stored, the code to create a List<ArrayList> would look something like this:

    // creates an ArrayList that holds ArrayLists
    List<ArrayList> allTheLists = new ArrayList<ArrayList>();
    allTheLists.add(yourList1);
    allTheLists.add(yourList2);
    ...
    allTheLists.add(yourList9);
    
    0 讨论(0)
提交回复
热议问题