java combine multiple lists

Java 8 has an easy way of Combine multiple lists with the help of Stream API.we have basically created a stream with all the lists and then use flatMap method will return a Stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.

				
					import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MulipleListAdd {
	public static void main(String[] args) {
		List list1 = Arrays.asList(2, 3, 4, 5);
		List list2 = Arrays.asList(21, 31, 41, 51);
		List list3 = Arrays.asList(20, 30, 40, 50);
		List combinedList = (List) Stream.of(list1, list2, list3).flatMap(x -> x.stream()).collect(Collectors.toList());
		System.out.println("Combined All List :- " + combinedList);

	}
}
				
			

Output :-
Combined All List :- [2, 3, 4, 5, 21, 31, 41, 51, 20, 30, 40, 50]

Leave a Comment

Your email address will not be published. Required fields are marked *