简体   繁体   中英

Sort 2d ArrayList by the length of the sub ArrayList

I have a two dimensional array:

ArrayList<List<Integer>> main= new ArrayList<>();    
ArrayList<Integer> sub=new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
.............

now main array looks like

  main-> [[1,2],[3],[4,5,6],[6,6,8,4]]

Now I want to sort array by length of the sub array. How can i get following result? Or is there a way to get max element length [in this case 4] of the sub-array without going through a loop? Can I get 4 without looping ? I need to sort but if it's not possible I want to get max length of sub array maxlength=4 ;

[[6,6,8,4],[4,5,6],[1,2],[3]]

Here is one way to sort by the lengths of the sub lists:

You can create a Comparator for two ArrayList<Integer> that compares their lengths and use it as the comparator parameter in Collections.sort()

class LengthComparator implements Comparator<ArrayList<Integer>> {
    public int compare(ArrayList<Integer> list1, ArrayList<Integer> list2) {
        return list2.size() - list1.size(); // sort descending in length
    }
}

// ...

ArrayList<ArrayList<Integer>> mainList;

// ... initialization, adding data

// sort
Collections.sort(mainList, new LengthComparator());

As far as getting the max without looping... not really. I mean you can iterate through a structure in a different way other than looping (recursion for example) but in the end you have to check each element...

Think about it, how can you know if something has the maximum value in a group if you don't compare it with everything else in the group?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM