0 votes
in Java by
Merging two arrayLists into a new arrayList, with no duplicates in Java

1 Answer

0 votes
by (2.8k points)

If you want to merge two or more arraylists into a new arraylist with no duplicates then java8 provides us a method distinct(). The distinct() method removes all duplicate during merge the list.

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())



        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);




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, f, 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.