Languages
[Edit]
EN

Java - merge two Lists into HashSet

0 points
Created by:
Dirask Community
6360

In this article, we would like to show you how to merge two Lists into the HashSet in Java.

Quick solution:

Set<String> mySet = new HashSet<>(myArrayList1);
mySet.addAll(myArrayList2);

 

Practical example

In this example, we merge letters1 and letters2 ArrayLists into alphabet HashSet using addAll() method.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        List<String> letters1 = new ArrayList<>();

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

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

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

        Set<String> alphabet = new HashSet<>(letters1);
        alphabet.addAll(letters2);

        System.out.println(alphabet);
    }
}

Output:

[A, B, C, D]
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join