Sorting an ArrayList of objects using a custom sorting order

后端 未结 11 1512
说谎
说谎 2020-11-22 00:14

I am looking to implement a sort feature for my address book application.

I want to sort an ArrayList contactArray. Contact

相关标签:
11条回答
  • 2020-11-22 00:51

    You shoud use the Arrays.sort function. The containing classes should implement Comparable.

    0 讨论(0)
  • 2020-11-22 00:54

    I did it by the following way. number and name are two arraylist. I have to sort name .If any change happen to name arralist order then the number arraylist also change its order.

    public void sortval(){
    
            String tempname="",tempnum="";
    
             if (name.size()>1) // check if the number of orders is larger than 1
                {
                    for (int x=0; x<name.size(); x++) // bubble sort outer loop
                    {
                        for (int i=0; i < name.size()-x-1; i++) {
                            if (name.get(i).compareTo(name.get(i+1)) > 0)
                            {
    
                                tempname = name.get(i);
    
                                tempnum=number.get(i);
    
    
                               name.set(i,name.get(i+1) );
                               name.set(i+1, tempname);
    
                                number.set(i,number.get(i+1) );
                                number.set(i+1, tempnum);
    
    
                            }
                        }
                    }
                }
    
    
    
    }
    
    0 讨论(0)
  • 2020-11-22 00:55

    You need make your Contact classes implement Comparable, and then implement the compareTo(Contact) method. That way, the Collections.sort will be able to sort them for you. Per the page I linked to, compareTo 'returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.'

    For example, if you wanted to sort by name (A to Z), your class would look like this:

    public class Contact implements Comparable<Contact> {
    
        private String name;
    
        // all the other attributes and methods
    
        public compareTo(Contact other) {
            return this.name.compareTo(other.name);
        }
    }
    
    0 讨论(0)
  • 2020-11-22 00:55

    The Collections.sort is a good sort implementation. If you don't have The comparable implemented for Contact, you will need to pass in a Comparator implementation

    Of note:

    The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n log(n) performance. The specified list must be modifiable, but need not be resizable. This implementation dumps the specified list into an array, sorts the array, and iterates over the list resetting each element from the corresponding position in the array. This avoids the n2 log(n) performance that would result from attempting to sort a linked list in place.

    The merge sort is probably better than most search algorithm you can do.

    0 讨论(0)
  • 2020-11-22 00:59

    In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:

    Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
    

    or since List now have sort method

    yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
    

    Explanation:

    Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:

    • lambdas arguments -> body
    • or method references source::method.

    Since Comparator<T> has only one abstract method int compare(T o1, T o2) it is functional interface.

    So instead of (example from @BalusC answer)

    Collections.sort(contacts, new Comparator<Contact>() {
        public int compare(Contact one, Contact other) {
            return one.getAddress().compareTo(other.getAddress());
        }
    }); 
    

    we can reduce this code to:

    Collections.sort(contacts, (Contact one, Contact other) -> {
         return one.getAddress().compareTo(other.getAddress());
    });
    

    We can simplify this (or any) lambda by skipping

    • argument types (Java will infer them based on method signature)
    • or {return ... }

    So instead of

    (Contact one, Contact other) -> {
         return one.getAddress().compareTo(other.getAddress();
    }
    

    we can write

    (one, other) -> one.getAddress().compareTo(other.getAddress())
    

    Also now Comparator has static methods like comparing(FunctionToComparableValue) or comparing(FunctionToValue, ValueComparator) which we could use to easily create Comparators which should compare some specific values from objects.

    In other words we can rewrite above code as

    Collections.sort(contacts, Comparator.comparing(Contact::getAddress)); 
    //assuming that Address implements Comparable (provides default order).
    
    0 讨论(0)
提交回复
热议问题