How do I join two lists in Java?

后端 未结 30 1720
旧巷少年郎
旧巷少年郎 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:21

    Here is a java 8 solution using two lines:

    List newList = new ArrayList<>();
    Stream.of(list1, list2).forEach(newList::addAll);
    
    
    

    Be aware that this method should not be used if

    • the origin of newList is not known and it may already be shared with other threads
    • the stream that modifies newList is a parallel stream and access to newList is not synchronized or threadsafe

    due to side effect considerations.

    Both of the above conditions do not apply for the above case of joining two lists, so this is safe.

    Based on this answer to another question.

    提交回复
    热议问题