1

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

Libathos
  • 3,340
  • 5
  • 36
  • 61

2 Answers2

3

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]
jervine10
  • 3,039
  • 22
  • 35
  • yes but this doesn't ensure that it will be grouped. for example: if the list is 1,2,3,4,1 this will return: 1,2,3,1,4 – Libathos Feb 24 '14 at 13:43
  • I don't believe that is true. Have you run a unit test with that assertion? – jervine10 Feb 24 '14 at 13:48
  • sorry my bad, I implemented something similar and didn't work.In you're SortTest why where did you declare that will use the abobe comparator? – Libathos Feb 24 '14 at 13:53
  • I didn't. My list contains Integers, and we get Integer comparison for free in java. The comparator I provided you actually uses Integer comparison to give you the result you're after. Have your Monument class implement the Comparator interface just like I showed you. Then all you'll need to do is call Collections.sort(list) to get them sorted. – jervine10 Feb 24 '14 at 13:56
1

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;
}
lance-java
  • 25,497
  • 4
  • 59
  • 101