How do I join two lists in Java?

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

    You can create your generic Java 8 utility method to concat any number of lists.

    @SafeVarargs
    public static <T> List<T> concat(List<T>... lists) {
        return Stream.of(lists).flatMap(List::stream).collect(Collectors.toList());
    }
    
    0 讨论(0)
  • 2020-11-22 15:21

    Here is a java 8 solution using two lines:

    List<Object> 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.

    0 讨论(0)
  • 2020-11-22 15:22

    Probably not simpler, but intriguing and ugly:

    List<String> newList = new ArrayList<String>() { { addAll(listOne); addAll(listTwo); } };
    

    Don't use it in production code... ;)

    0 讨论(0)
  • 2020-11-22 15:22

    In Java 8 (the other way):

    List<?> newList = 
    Stream.of(list1, list2).flatMap(List::stream).collect(Collectors.toList());
    
    0 讨论(0)
  • 2020-11-22 15:24

    I'm not claiming that it's simple, but you mentioned bonus for one-liners ;-)

    Collection mergedList = Collections.list(new sun.misc.CompoundEnumeration(new Enumeration[] {
        new Vector(list1).elements(),
        new Vector(list2).elements(),
        ...
    }))
    
    0 讨论(0)
  • 2020-11-22 15:25

    Off the top of my head, I can shorten it by one line:

    List<String> newList = new ArrayList<String>(listOne);
    newList.addAll(listTwo);
    
    0 讨论(0)
提交回复
热议问题