Creating prepopulated set in Java

The easiest way, using standard Java classes, is

static final Set<Integer> NECESSARY_PERMISSIONS = 
    Collections.unmodifiableSet(new HashSet<Integer>(Arrays.asList(1, 2, 3, 6)));

But you can also use a static initializer, or delegate to a private static method:

static final Set<Integer> NECESSARY_PERMISSIONS = createNecessaryPermissions();

Note the unmodifiableSet wrapper, which guarantees that your constant set is indeed constant.


You might consider using Guava's ImmutableSet:

static final Set<Integer> NECESSARY_PERMISSIONS = ImmutableSet.<Integer>builder()
        .add(1)
        .add(2)
        .add(3)
        .add(6)
        .build();
static final Set<String> FOO = ImmutableSet.of("foo", "bar", "baz");

Among other things, this is significantly faster (and ~3 times more space-efficient) than HashSet.


Using Google Guava library you can use ImmutableSet, which is designed exactly to this case (constant values):

static final ImmutableSet<Integer> NECESSARY_PERMISSIONS =
        ImmutableSet.of(1,2,3,6);

Old-school way (without any library):

static final Set<Integer> NECESSARY_PERMISSIONS =
        new HashSet<Integer>(Arrays.asList(1,2,3,6));

EDIT:

In Java 9+ you can use Immutable Set Static Factory Methods:

static final Set<Integer> NECESSARY_PERMISSIONS =
        Set.of(1,2,3,6);

Try this idiom:

import java.util.Arrays;

new HashSet<Integer>(Arrays.asList(1, 2, 3, 6))