Many times in your work you need to merge two lists and remove duplicates. This is a very simple operation, and the main thing here is to document this operation by using Stream.

Before java8, it was common to add two lists to a Set. Since the contents of a Set were not repeatable, it was automatically de-duplicated, and then the Set was converted to a List, as follows:

        Set<String> set = new HashSet<>(listA);
        set.addAll(listB);
        List<String> list = new ArrayList<>(set);
        System.out.println(list);Copy the code

The list after doing this is the result of merging and de-recasting.

After java8 came along, we had a much more efficient way to do this with a Stream:

        List<String> collect = Stream.of(listA, listB)
                .flatMap(Collection::stream)
                .distinct()
                .collect(Collectors.toList());Copy the code

The result is what we want in the end, and it’s clear that the code done through Stream looks cleaner and smoother.

Tip: Be careful to override equals and HashCode methods if you want to merge objects.

The attached:

Complete code for reference.

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Combine {

    public static void main(String[] args) {

        String[] arr1 = {"a"."b"."c"."d"."e"."f"};
        List<String> listA = new ArrayList<>(Arrays.asList(arr1));

        String[] arr2 = {"d"."e"."f"."g"."h"};
        List<String> listB = new ArrayList<>(Arrays.asList(arr2));

        Set<String> set = new HashSet<>(listA);
        set.addAll(listB);
        List<String> list = new ArrayList<>(set); System.out.println(list); List<String> collect = Stream.of(listA, listB) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()); System.out.println(collect); }}Copy the code