How do I join two lists in Java?

后端 未结 30 2048
旧巷少年郎
旧巷少年郎 2020-11-22 14:36

Conditions: do not modifiy the original lists; JDK only, no external libraries. Bonus points for a one-liner or a JDK 1.3 version.

Is there a simpler way than:

30条回答
  •  春和景丽
    2020-11-22 15:26

    If you want to do this statically you can the following.

    The examples uses 2 EnumSets in natural-order (==Enum-order) A, B and joins then in an ALL list.

    public static final EnumSet CATEGORY_A = EnumSet.of(A_1, A_2);
    public static final EnumSet CATEGORY_B = EnumSet.of(B_1, B_2, B_3);
    
    public static final List ALL = 
                  Collections.unmodifiableList(
                      new ArrayList(CATEGORY_A.size() + CATEGORY_B.size())
                      {{
                          addAll(CATEGORY_A);
                          addAll(CATEGORY_B);
                      }}
                  );
    

提交回复
热议问题