How do I join two lists in Java?

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

    We can join 2 lists using java8 with 2 approaches.

        List list1 = Arrays.asList("S", "T");
        List list2 = Arrays.asList("U", "V");
    

    1) Using concat :

        List collect2 = Stream.concat(list1.stream(), list2.stream()).collect(toList());
        System.out.println("collect2 = " + collect2); // collect2 = [S, T, U, V]
    

    2) Using flatMap :

        List collect3 = Stream.of(list1, list2).flatMap(Collection::stream).collect(toList());
        System.out.println("collect3 = " + collect3); // collect3 = [S, T, U, V]
    

提交回复
热议问题