How do I join two lists in Java?

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

    Java 8 (Stream.of and Stream.concat)

    The proposed solution is for three lists though it can be applied for two lists as well. In Java 8 we can make use of Stream.of or Stream.concat as:

    List result1 = Stream.concat(Stream.concat(list1.stream(),list2.stream()),list3.stream()).collect(Collectors.toList());
    List result2 = Stream.of(list1,list2,list3).flatMap(Collection::stream).collect(Collectors.toList());
    

    Stream.concat takes two streams as input and creates a lazily concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream. As we have three lists we have used this method (Stream.concat) two times.

    We can also write a utility class with a method that takes any number of lists (using varargs) and returns a concatenated list as:

    public static  List concatenateLists(List... collections) {
            return Arrays.stream(collections).flatMap(Collection::stream).collect(Collectors.toList()); 
    }
    

    Then we can make use of this method as:

    List result3 = Utils.concatenateLists(list1,list2,list3);
    

提交回复
热议问题