Comment combiner (fusionner) des listes en Java8. Quand je l'ai recherché, il y en avait trois.
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