Java – Combine List using stream

A Stream of items that are in turn streamable can be flattened into a single continuous Stream. Using approach Lists can be combined and converted into a single list.

 
package com.pwn.stream;

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

/*Flatten Streams with flatMap()*/
public class FlatMap {

	public static void main(String[] args) {

		List<String> list1 = Arrays.asList("1", "2");
		List<String> list2 = Arrays.asList("3", "4", "5");
		List<String> list3 = Arrays.asList("6");
		List<String> finalList = Stream.of(list1, list2, list3)
				.flatMap(Collection::stream)
				.collect(Collectors.toList());
		System.out.println(finalList);

	}

}

[1, 2, 3, 4, 5, 6]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s