I'm looking to simplify the initialisation of the second constant, preferably to just one line. Any ideas? Anything from Guava or JDK (up to 1.6) is ok to use.
enum Box {
PROMO_HEADER,
FREEMIUM,
EXTRA_STORIES,
TOP_STORIES,
TOP_CHARACTERS,
TOP_THEMES,
TOP_ARTISTS,
TOP_ISSUES
// several more ...
}
final static List<Box> FREEMIUM_BOXES = ImmutableList.copyOf(Box.values());
final static List<Box> DEFAULT_BOXES = initDefaultBoxes(); // All except FREEMIUM
static List<Box> initDefaultBoxes() {
List<Box> boxes = Lists.newArrayList(FREEMIUM_BOXES);
boxes.remove(Box.FREEMIUM);
return ImmutableList.copyOf(boxes);
}
Granted, it's not that bad, but still I'd like to get rid of the init method. :-) (Static initialiser wouldn't be any better.)
NB: I want to define the order of boxes only once, in the enum definition itself, so ImmutableList.of(PROMO_HEADER, EXTRA_STORIES, ...)
is not considered a good solution for the purposes of this refactoring.
A single-statement Guava solution would be this, using filter()
and a Predicate, but arguably this is less clean than the original, because this kind of stuff is verbose in Java...
final static List<Box> DEFAULT_BOXES =
ImmutableList.copyOf(Iterables.filter(FREEMIUM_BOXES, new Predicate<Box>() {
@Override
public boolean apply(Box box) {
return box != Box.FREEMIUM;
}
}));
Resolution
Went with this, which is the cleanest option considering I indeed need the constants defined as Lists:
final static List<Box> FREEMIUM_BOXES = ImmutableList.copyOf(Box.values());
final static List<Box> DEFAULT_BOXES =
Sets.immutableEnumSet(EnumSet.complementOf(EnumSet.of(Box.FREEMIUM))).asList();