简体   繁体   中英

How to sort an ArrayList by its elements size in Java?

So I have a List<String> L1 = new ArrayList<>() with the following strings as elements:

  • l, l, u, u.
  • r, u, d, l, d, l, u.
  • l, u, d, r, r, r, r, r, u, d.
  • l, u.
  • l, u, r.

How do I sort the list by its element's size so that in the final state L1 should be like this:

  • l, u.
  • l, u, r.
  • l, l, u, u.
  • r, u, d, l, d, l, u.
  • l, u, d, r, r, r, r, r, u, d.

I have tried using Collections.sort , but that sorts alphabetically, which is obviously not what I want.

I think what you are looking for is Collections.sort(java.util.List, java.util.Comparator) . With it you can specify a custom Comparator that compares the strings based on length instead of alphabetical relationship.

Something like this:

List<String> stringList = new ArrayList<String>();

// Fill the list

Comparator<String> stringLengthComparator = new Comparator<String>()
    {
        @Override
        public int compare(String o1, String o2)
        {
            return Integer.compare(o1.length(), o2.length());
        }
    };

Collections.sort(stringList, stringLengthComparator);

Assuming Java 8 is available, and also that the list is of type List<String> :

list.sort(Comparator.comparing(String::length));

This creates a new Comparator that uses the length of the string as the basis for sorting, then sorts according to it. The list is sorted from short to long, but if that's undesirable...

list.sort(Comparator.comparing(String::length).reversed());

...would invert it to sort the longest strings first.

If the list is actually a list of lists (the question is slightly unclear on that), List::size would be used instead of String::length .

You can use any sorting technique(bubble,insertion etc.) to sort the elements of Arraylist.Here I use bubble sort to sort the elements of Arraylist.

public class SortArray
{
    public static void main(String[] args)
    {   
        List<String> al = new ArrayList<String>();
        //add items to arraylist objects.
        al.add("l,l,u,u");
        al.add("r, u, d, l, d, l, u");
        al.add("l, u, d, r, r, r, r, r, u, d");
        al.add("l,u");
        al.add("l,u,r");

        //Use bubble sort here.
        for(int i=0;i<al.size();i++){
            for(int j=0;j<al.size()-i-1;j++){
                if( (al.get(j)).length() > (al.get(j+1)).length() ){
                    Collections.swap(al, j, j+1);
                }
            }
        }

        for(String str : al){
            System.out.println(str);
        }

    }
}

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