Combine Java8 lists

How to merge lists in Java8. When I looked it up, there were three.

import java.util.*;
import java.util.stream.*;

class Main {
    public static void main(String[] args) {
        List<String> list1 = Arrays.asList("Apple", "Banana", "Ctrus");
        List<String> list2 = Arrays.asList("Drian", "Elderberry");
        
        // (1) http://blog.64p.org/entry/2014/11/21/123447
        List<String> newList1 = Stream.concat(list1.stream(), list2.stream())
                                      .collect(Collectors.toList());
        System.out.println(newList1);
        
        // (2) http://simplesandsamples.com/list-join.java.html
        List<String> newList2 = new ArrayList<>();
        newList2.addAll(list1);
        newList2.addAll(list2);
        System.out.println(newList2);
        
        // (3) https://ja.stackoverflow.com/questions/8232/stream%E3%81%A7%E3%83%AA%E3%82%B9%E3%83%88%E3%81%AE%E7%B5%90%E5%90%88%E3%81%8C%E3%81%97%E3%81%9F%E3%81%84
        List<List<String>> outer = Arrays.asList(list1, list2);
        List<String> newList3 = outer.stream()
            .flatMap(lst -> lst.stream())
            .collect(Collectors.toList());
        System.out.println(newList3);
    }
}

Recommended Posts

Combine Java8 lists
[Java] Combine multiple Lists (Collections)
Combine arrays in Java
Compare Lists in Java
Nesting Java Lists together
Study java arrays, lists, maps
Java
Java
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
Java review
java framework
Java features
[Java] Inheritance
FastScanner Java
Java features
java beginner 3
Java memo
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes