$show=/label

How To Join Two Or Combine More Lists In old and new Java 8 Steam API?

SHARE:

A quick and programming guide to join or combine two lists in java in different ways using addAll() and java 8 stream api with examples.

1. Overview

In this tutorial, you'll learn how to join or combine two lists in java. Typically, we are going to merge the two ArrayList values into a single list in various ways.

The simple one, just use addAll() method works well. But there are other options with java 8 api and apache commons library.

Let us start one by one approach.

How To Join Two Or Combine More Lists In old and new Java 8 Steam API?




2. Example - Join Two Lists - addAll()


First, let us work with a simple example program with addAll() method which takes Collection as an argument.
Collection means any object of implementation of List and Set interfaces such as ArrayList, HashSet etc.

In the below program,

First, Created list1 and added 5 string values using add() method.
Next, Created a second list list2 and added another 5 string values using add() method.

After that created third list joinedList which is to store the values of list1 and list2. Pass list1 to addAll() method and 
next, immediately call addAll() method with list2.

Finally, at this point, joinedList will have all values of list1 and list2.
import java.util.ArrayList;
import java.util.List;

public class JoinTwoListsAddAllExample {

	public static void main(String[] args) {
		// Creating list 1
		
		List<String> list1 = new ArrayList<>();
		
		list1.add("one");
		list1.add("two");
		list1.add("three");
		list1.add("four");
		list1.add("five");
		
		// creating list 2
		List<String> list2 = new ArrayList<>();
		
		list2.add("six");
		list2.add("seven");
		list2.add("eight");
		list2.add("nine");
		list2.add("ten");
		
		
		System.out.println("List1 values : "+list1);
		System.out.println("List2 values : "+list2);
		
		// Joining list1 and list2 into a one list with both list values.
		
		List<String> joinedList = new ArrayList<>();
		joinedList.addAll(list1);
		joinedList.addAll(list2);
		
		// printing the merged list
		System.out.println("Joined list : "+joinedList);
	}
}

Output:
List1 values : [one, two, three, four, five]
List2 values : [six, seven, eight, nine, ten]
Joined list : [one, two, three, four, five, six, seven, eight, nine, ten]
The same above code can be rewritten as below.

Alternatively, list1 can be passed directly to the ArrayList constructor that reduces the repeatedly calling the addAll() method.
List<String> joinedList = new ArrayList<>(list1);
joinedList.addAll(list2);

3. Example - Join Two Lists - Double Curly Brace Initializer 


The next approach is a little complex for java beginners. Use the double initializer at the ArrayList constructor that creates an anonymous inner class and all methods of ArrayList class are available from in it.

Let us the same input list1 and list2.

So, you can call addAll() method twice from it.
// using Double curly braces.
List<String>  joinedList2 = new ArrayList<String>() {{
	addAll(list1);
	addAll(list2);
}};

// printing the merged list
System.out.println("Joined list : "+joinedList2);

4. Example - Join Multiple Lists - Collections.addAll()

The third approach is to use the Collections.addAll() method which concatenates the multiple lists.
// creating list 3
List<String> list3 = new ArrayList<>();

list2.add("11");
list2.add("12");

List<String> multipleListsJoin = new ArrayList<>();

Collections.addAll(multipleListsJoin, list1.toArray(new String[0]));
Collections.addAll(multipleListsJoin, list2.toArray(new String[0]));
Collections.addAll(multipleListsJoin, list3.toArray(new String[0]));

System.out.println("Joining multiple lists : "+multipleListsJoin);

Output:
Joining multiple lists : [one, two, three, four, five, six, seven, eight, nine, ten, 11, 12]

5. Example - Join Two Lists - Java 8 Stream API


Java 8 Stream API has several methods combinations to join two lists.

All below examples take two lists list1 and list2 type of String.

5.1 Using Stream.concat() + collect() Method


First, convert the List into Stream using steam() method and call Stream.concat() method to merge two streams.

Finally, call Collectors.toList() method to convert Stream to List.
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class JoinTwoListsJava8Example {

	public static void main(String[] args) {
		// Creating list 1

		List<String> list1 = new ArrayList<>();

		list1.add("manog");
		list1.add("banana");

		// creating list 2
		List<String> list2 = new ArrayList<>();

		list2.add("apple");
		list2.add("orange");

		// Stream.concat() method.
		
		Stream<String> stream1 = list1.stream();
		Stream<String> stream2= list2.stream();
		
		List<String> joinedList = Stream.concat(stream1, stream2).collect(Collectors.toList());
		
		System.out.println("Joined list values : "+joinedList);
		

	}

}

Output:
Joined list values : [manog, banana, apple, orange]

5.2 Using Stream.of() + flatMap() Method


Call the flatMap() method on stream object and next collect the output into list using Collectors.toList().
// way 2 Stream.flatMap() method.

List<String> joinedList2 = Stream.of(list1, list2).flatMap(list -> list.stream()).collect(Collectors.toList());

System.out.println("Joined list values using flatMap() : " + joinedList2);

5.3 Using Stream.of() + Stream.forEach() method


// way 3 Stream.flatMap() method.
List<String> joinedList3  = new ArrayList<>();
Stream.of(list1, list2).forEach(joinedList3::addAll);

System.out.println("Joined list values using forEach() : " + joinedList3);

6. Example - Join Two Lists - Using Apache Commons ListUtils


Apache commons api has a ListUtils class with union() method which takes two list objects and returns the merged list.

This method is implemented internally using the first approach.
import org.apache.commons.collections4.ListUtils;

public class JoinTwoListsutilsExample {

	public static void main(String[] args) {
		// Creating list 1

		List<String> list1 = new ArrayList<>();

		list1.add("A");
		list1.add("B");

		// creating list 2
		List<String> list2 = new ArrayList<>();

		list2.add("C");
		list2.add("D");

		// adding two list values into one using ListUtils.union() method
		List<String> unionOfLists = ListUtils.union(list1, list2);
		
		System.out.println("List 1 values : "+list1);
		System.out.println("List 2 values : "+list2);
		System.out.println("ListUtils union list values : "+unionOfLists);

	}

}
Output:
List 1 values : [A, B]
List 2 values : [C, D]
ListUtils union list values : [A, B, C, D]

7. Conclusion


In this article, you've seen the different ways to join or merge two lists in java and stream API. And also example on apache ListUtils.union() method.

GitHub


Ref



COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,18,Arrays,24,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,8,Collections,37,Collector,1,Command Line,1,Comparator,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,149,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,38,Dictionary,1,Difference,2,Download,1,Eclipse,3,Efficiently,1,Error,1,Errors,1,Exceptions,8,Fast,1,Files,17,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,9,Grant,1,Grep,1,HashMap,2,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,6,Iterate,2,Jackson API,3,Java,32,Java 10,1,Java 11,6,Java 12,5,Java 13,2,Java 14,2,Java 8,128,Java 8 Difference,2,Java 8 Stream Conversions,4,java 8 Stream Examples,12,Java 9,1,Java Conversions,14,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,114,Java Spark,1,java.lang,4,java.util. function,1,JavaScript,1,jQuery,1,Kotlin,11,Kotlin Conversions,6,Kotlin Programs,10,Lambda,2,lang,29,Leap Year,1,live updates,1,LocalDate,1,Logging,1,Mac OS,3,Math,1,Matrix,6,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,2,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,31,String,61,String Programs,28,String Revese,1,StringBuilder,1,Swing,1,System,1,Tags,1,Threads,11,Tomcat,1,Tomcat 8,1,Troubleshoot,26,Unix,3,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: How To Join Two Or Combine More Lists In old and new Java 8 Steam API?
How To Join Two Or Combine More Lists In old and new Java 8 Steam API?
A quick and programming guide to join or combine two lists in java in different ways using addAll() and java 8 stream api with examples.
https://blogger.googleusercontent.com/img/a/AVvXsEhpzd-W2qjN9nh9XN05YA6qrqVb_-5yzCG3Xlsw3QXWndplmVFqNmGIc1jOe_9EKdikMmvclhiASA4fNLJr8jSQFlQrz0zIt-_QKhKjWvcWo0TTPYxPOAu3YBVzpYAIRUGMXcdztz8hkBCbHgTaKxyJFhFpdPuS4X01QefZ5sSEoucojpW-zOblrXVs=w400-h219
https://blogger.googleusercontent.com/img/a/AVvXsEhpzd-W2qjN9nh9XN05YA6qrqVb_-5yzCG3Xlsw3QXWndplmVFqNmGIc1jOe_9EKdikMmvclhiASA4fNLJr8jSQFlQrz0zIt-_QKhKjWvcWo0TTPYxPOAu3YBVzpYAIRUGMXcdztz8hkBCbHgTaKxyJFhFpdPuS4X01QefZ5sSEoucojpW-zOblrXVs=s72-w400-c-h219
JavaProgramTo.com
https://www.javaprogramto.com/2020/11/java-join-two-lists.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/11/java-join-two-lists.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content