How to group elements in ArrayList

2019-06-06 09:10发布

问题:

Is there a simple and fast way to group elements from an ArrayList in Java? I'm asking if there is already a way without implementing it by my self? something like

Collections.sort(monuments,new objectComparator());

EDIT: I have a list of Objects That have a field called category, this list is shown to the user. I want the objects of category_type==1 to be shown first and so on.

I can't achieve this with comparator, since the way the comparator works is like this:

return int a>0 if the first value is bigger return int a

回答1:

Actually this can be achieved with a comparator:

public int compareTo(Monument o) {
    Integer otherCategory = o.getCategoryType();
    Integer thisCategory = this.getCategoryType();
    return thisCategory.compareTo(otherCategory);
}

The Comparator will return 0 if they are the same, -1 if thisCategory is less than otherCategory, and 1 if thisCategory is greater than otherCategory

Here's a unit test based on this idea:

public class SortTest {

    @Test
    public void test() {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(1);

        System.out.println("Unsorted: " + list);

        Collections.sort(list);

        System.out.println("Sorted: " + list);
    }

}

Output:

Unsorted: [1, 2, 3, 4, 1]
Sorted: [1, 1, 2, 3, 4]


回答2:

Try grouping using a Map<X, List<CustomObject>> where X is the grouping (in your case an Integer representing the category_type)

eg:

public Map<Integer, List<CustomObject>> groupByCategoryType(List<CustomObject> list) {
    Map<Integer, List<CustomObject>> map = new TreeMap<Integer, List<CustomObject>>();
    for (CustomObject o : list) {
        List<CustomObject> group = map.get(o.getCategoryType());
        if (group == null) {
           group = new ArrayList();
           map.put(o.getCategoryType(), group);
        }
        group.add(o);
    }
    return map;
}