【问题标题】:Deriving a list from a given list with additional elements从具有附加元素的给定列表派生列表
【发布时间】:2018-04-17 08:15:58
【问题描述】:

我正在维护一个类来保持所有字段的外部化。一个包含多个此类值及其集合的示例类是:

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);
}

可以看出IRREVERSIBLE_STATES 拥有IMMUTABLE_STATES 拥有的所有字段(状态)。此外,它还有一些自己的额外功能,在本例中为 PENDING

有没有办法优雅地初始化第二个列表,以便它直接从第一个列表中获取值,而不是再次声明所有常见状态?我必须编写一个方法来实现这一点吗?不能作为初始化器在一行中完成吗?

【问题讨论】:

  • List&lt;String&gt; IRREVERSIBLE_STATES = new ArrayList&lt;&gt;(IMMUTABLE_STATES ) 怎么样?顺便说一句,我会在这里使用enum

标签: java list arraylist collections java-8


【解决方案1】:

虽然连接流在这里可以工作, 一个更简单的解决方案是使用静态初始化器:

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

【讨论】:

    【解决方案2】:

    使用流怎么样?

    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());
    

    此外,您的“状态”感觉应该是 enums,而不是字符串。

    【讨论】:

    • 不错。流很好
    猜你喜欢
    • 2022-01-13
    • 2021-05-19
    • 2016-10-03
    • 1970-01-01
    • 2016-09-17
    • 1970-01-01
    • 2016-05-26
    • 2017-12-18
    • 1970-01-01
    相关资源
    最近更新 更多