How can I sort an ArrayList of Strings in Java?

后端 未结 5 1086
遥遥无期
遥遥无期 2020-11-30 09:21

I have Strings that are put into an ArrayList randomly.

private ArrayList teamsName = new ArrayList();
         


        
相关标签:
5条回答
  • 2020-11-30 10:02

    Check Collections#sort method. This automatically sorts your list according to natural ordering. You can apply this method on each sublist you obtain using List#subList method.

    private List<String> teamsName = new ArrayList<String>();
    List<String> subList = teamsName.subList(1, teamsName.size());
    Collections.sort(subList);
    
    0 讨论(0)
  • 2020-11-30 10:03
    Collections.sort(teamsName.subList(1, teamsName.size()));
    

    The code above will reflect the actual sublist of your original list sorted.

    0 讨论(0)
  • 2020-11-30 10:04

    You can use TreeSet that automatically order list values:

    import java.util.Iterator;
    import java.util.TreeSet;
    
    public class TreeSetExample {
    
        public static void main(String[] args) {
            System.out.println("Tree Set Example!\n");
    
            TreeSet <String>tree = new TreeSet<String>();
            tree.add("aaa");
            tree.add("acbbb");
            tree.add("aab");
            tree.add("c");
            tree.add("a");
    
            Iterator iterator;
            iterator = tree.iterator();
    
            System.out.print("Tree set data: ");
    
            //Displaying the Tree set data
            while (iterator.hasNext()){
                System.out.print(iterator.next() + " ");
            }
        }
    
    }
    

    I lastly add 'a' but last element must be 'c'.

    0 讨论(0)
  • 2020-11-30 10:23

    You might sort the helper[] array directly:

    java.util.Arrays.sort(helper, 1, helper.length);
    

    Sorts the array from index 1 to the end. Leaves the first item at index 0 untouched.

    See Arrays.sort(Object[] a, int fromIndex, int toIndex)

    0 讨论(0)
  • 2020-11-30 10:25

    Take a look at the Collections.sort(List<T> list).

    You can simply remove the first element, sort the list and then add it back again.

    0 讨论(0)
提交回复
热议问题