Akeshwar Jha
Akeshwar Jha

Reputation: 4576

Deriving a list from a given list with additional elements

I am maintaining a class to keep all the fields externalized. A sample class which holds several such values and their collections is:

public static class State {
    public static final String DRAFT = "DRAFT";
    public static final String APPROVED = "APPROVED";
    public static final String RECEIVED = "RECEIVED";
    public static final String PENDING = "PENDING";

    public static List<String> IMMUTABLE_STATES = Arrays.asList(APPROVED,RECEIVED);
    public static List<String> IRREVERSIBLE_STATES = Arrays.asList(DRAFT,RECEIEVED,PENDING);
}

As it can be seen that IRREVERSIBLE_STATES has all the fields (states) which IMMUTABLE_STATES has. Plus, it has some extra of its own, PENDING in this case.

Is there a way to elegantly initialize the second list so that it directly takes the values from the first list instead of declaring all the common states again? Do I have to write a method to achieve this? Can't it be done in one line as an initializer?

Upvotes: 1

Views: 55

Answers (2)

janos
janos

Reputation: 124804

Although concatenating streams would work here, a simpler solution is using a static initializer:

public static List<String> IRREVERSIBLE_STATES = new ArrayList<>(IMMUTABLE_STATES);
static {
    IRREVERSIBLE_STATES.addAll(Arrays.asList(DRAFT, PENDING));
}

Upvotes: 1

Malt
Malt

Reputation: 30335

How about using streams?

public static List<String> LIST1 = Arrays.asList("1", "2");
public static List<String> LIST2 = Stream.concat(LIST1.stream(), Arrays.asList("3", "4").stream())
            .collect(Collectors.toList());

Also, your "states" feel like they should be enums, not Strings.

Upvotes: 4

Related Questions