0 votes
128 views
in Java by

Merge two or more arraylist in java8.

A: [a, b, c, d, e]
B: [a, b, c, f, g]
C: [a, g, k, m, t]

Output: - [a, b, c, d, e, a, b, c, f, g, a, g, k, m, t]

1 Answer

0 votes
by (2.8k points)

Java8 provides us a method Stream’s flatMap(). The flatMap() method can be used to get the elements of two or more lists in single stream, and then collect stream elements to an arraylist.

package java8.com.dev.example.arraylist;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;

import java.util.stream.Stream;

public class MergeTwoArrayList {

public static void main(String[] args) {

ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e"));

        ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "f", "g"));

        ArrayList<String> listThird = new ArrayList<>(Arrays.asList("a", "g", "k", "m", "t"));

        List<String> combinedList = Stream.of(listOne, listTwo, listThird)

                                        .flatMap(x -> x.stream())

                                        .collect(Collectors.toList());

        System.out.println("First Array List: " + listOne);

        System.out.println("Second Array List: " + listTwo);

        System.out.println("Third Array List: " + listThird);

        System.out.println("After Merge Array List: " + combinedList);

}

}

Output:- 

First Array List: [a, b, c, d, e]

Second Array List: [a, b, c, f, g]

Third Array List: [a, g, k, m, t]

After Merge Array List: [a, b, c, d, e, a, b, c, f, g, a, g, k, m, t]

Share:- Whatsapp Facebook Facebook


Welcome to Developerhelpway Q&A, where you can ask questions and receive answers from other members of the community.

Categories

...