Reputation: 433
I need to order my List with 'Foo' objects based on a Enum value that Foo has as an attribute. I found 'Comparators', and I have used them before. But I always had some integer / double attribute, which is more clearer for me.
Because this question might be vague, i'll make some spoonfed code so you guys can see what I mean / want. Thanks a bunch!
/* Enum class */
public enum SomeEnum {
CONSTANT_ALPHA, CONSTANT_BETA, CONSTANT_DELTA;
}
/* Class 'Foo', this is my Foo object */
public class Foo {
private SomeEnum enum; /* Every 'Foo' has a enum type */
public Foo(SomeEnum enum){
this.enum = enum;
}
public SomeEnum getEnum(){
return enun;
}
}
/* Imagine this below is some controller class*/
Foo alpha1 = new Foo(SomeEnum.CONSTANT_ALPHA);
Foo beta1 = new Foo(SomeEnum.CONSTANT_BETA);
Foo alpha2 = new Foo(SomeEnum.CONSTANT_ALPHA);
Foo delta1 = new Foo(SomeEnum.CONSTANT_DELTA);
Foo beta2 = new Foo(SomeEnum.CONSTANT_BETA);
List<Foo> list = new ArrayList<>();
list.add(alpha1);
//list.add(beta1) etc etc (all those 5 Foos)
Collections.sort(list, someComparatorIDontKnowHowToMake);
System.out.println(list.toString()); /* Not sure how to correctly print a List<> object, but imagine I would print the contents of the list*/
/* The result of the list should be: */
/* alpha1, alpha2, beta1, beta2, delta1*/
In conclusion or TL;DR:
I need to order the objects in the list based with the same Enum types. I do not need to have 'alpha' before 'delta' specifically. I just want that the Foo objects that have the same enum value are next to eachother in the List.
If this didn't make sense, please do ask!
Thanks.
Upvotes: 1
Views: 1405
Reputation: 963
Can't test the code right know, so there might be some syntax issues, but to the point: enum instances are distinct integers, so you can compare Foo instances just by them.
Collections.sort(list, new Comparator<Foo>(){
public compare(Foo first, Foo second){
return first.getEnum().comapareTo(second.getEnum());
}
});
for(Foo item : list){
System.out.println(item);
}
Note that this code assumes that getEnum() won't return null for any instance in the list and that you will have toString() method implemented for Foo.
edit, yep, always too late.
Upvotes: 2
Reputation: 22972
You can simply compare enum
elements of Foo
foos.sort(new Comparator<Foo>() {
@Override
public int compare(Foo o1, Foo o2) {
//Add null check
return o1.getEnum().compareTo(o2.getEnum());
}
});
Upvotes: 2