简体   繁体   中英

Sorting an ArrayList, into object type and then alphabetically

I have defined an arrayList

Each of these objects have there own name etc. I would like to sort them by type, so all watermelons are together and pears are together etc. then for them to be sorted alphabetically within each time.

Something using

public int compare(String[] first, String[] second) {
    return first[1].compareTo(second[1]);
}

Also is it possible to just do this in an already created class, to avoid doing it in a new class.

Close, but you won't be able to pass String arrays as parameters to the compare method. You need to create a Comparator<Food> and the parameters will be Food references.

Then in the compare(Food f1, Food f2) method you'll need to compare the class, and if they're the same, then the name.

You are pretty close. You can do something like this (one-shot with anonymous implementation of Comparator interface so you don't need a new class):

Collections.sort(foodList, new Comparator<Food>() {
    @Override
    public int compare(Food food1, Food food2) {
        int result = 0;
        if(food1.getType().equals(food2.getType())) {
            result = food1.getName().compareTo(food2.getName());
        } else {
            result = food1.getType().compareTo(food2.getType()); 
        }

        return result;
    }
});

Another way is to have Food implement Comparable<T> and use the same logic for the compareTo(T o) implementation.

The comparison works by first checking to see if the types of the food are equal (assuming the food type has an applicable equals() method). If they are equal, the comparison needs to be done on the basis of their names. Otherwise, the comparison will be done based on the food type.

You can implement the Comparable interface in your Food implementations or subclasses. Though it is easy to write an implementation that works for your case, it is not as trivial as it seems to write a completely correct Comparable implementation, especially concerning inheritance. See Effective Java , item 12 for a good documentation of the requirements and of common pitfalls.

Your compare method name is wrong. It would be compareTo of Comparable interface.:

public int compareTo(Fruit second) {
 return this.getWaterMelon().compareTo(second.getWaterMelon());
}

I would say that your compare() method will need to return weighed value for your type compareTo() difference + name compareTo() difference.
Something like

public int compare(Food food1, Food food2) {
   int result = 0;
   result = food1.getType().compareTo(food2.getType()) * someMultiplier + food1.getName().compareTo(food2.getName());
   return result;
}

EDIT: This is the usage that I was suggesting...

public class ComparatorTest {

    static class ComaparableObject implements Comparable {
        private Object value1;
        private Object value2;

        public ComaparableObject(Object value1, Object value2) {
            this.value1 = value1;
            this.value2 = value2;
        }

        @Override
        public int compareTo(Object o) {
            int multiplier = 65535;
            ComaparableObject co = (ComaparableObject) o;
            int result = (value1.hashCode() * multiplier + value2.hashCode()) - (co.value1.hashCode() * multiplier + co.value2.hashCode()) ;
            return result;
        }

        public Object getValue1() {
            return value1;
        }

        public void setValue1(Object value1) {
            this.value1 = value1;
        }

        public Object getValue2() {
            return value2;
        }

        public void setValue2(Object value2) {
            this.value2 = value2;
        }

        public String toString() {
            String result = "value1=" + value1 + ", " + "value2=" + value2;
            return result;
        }

    }

    public static void main(String[] args) {
        ArrayList<ComaparableObject> al;


        al = new ArrayList<ComaparableObject>();
        ComaparableObject co;
        int value1 = 2;
        co = new ComaparableObject(value1, 3);
        al.add(co);
        co = new ComaparableObject(value1, 1);
        al.add(co);
        co = new ComaparableObject(value1, 2);
        al.add(co);
        value1 = 1;
        co = new ComaparableObject(value1, 3);
        al.add(co);
        co = new ComaparableObject(value1, 1);
        al.add(co);
        co = new ComaparableObject(value1, 2);
        al.add(co);

        System.out.println("Before sort: " + al);

        Collections.sort(al, new Comparator<ComaparableObject>() {
            @Override
            public int compare(ComaparableObject co1, ComaparableObject co2) {
                int result;
                result = co1.compareTo(co2);
                return result;
            }
        });

        System.out.println("After sort: " + al);

        }

}

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