Write a Java Program to Calculate union of two sets

Java Program to Calculate union of two sets

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Calculate union of two sets
Java Program to Calculate union of two sets

Write a Java Program to Calculate union of two sets

PROGRAM: Java Program to Calculate union of two sets

/*Java Program to Calculate union of two sets*/

1: Calculate the union of two sets using addAll()

import java.util.HashSet;
import java.util.Set;

class Main {
public static void main(String[] args) {

// create the first set
Set<Integer> evenNumbers = new HashSet<>();
evenNumbers.add(2);
evenNumbers.add(4);
System.out.println(“Set1: ” + evenNumbers);

// create second set
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(3);
System.out.println(“Set2: ” + numbers);

// Union of two sets
numbers.addAll(evenNumbers);
System.out.println(“Union is: ” + numbers);
}
}

2: Get union of two sets using Guava Library

import java.util.HashSet;
import java.util.Set;
import com.google.common.collect.Sets;

class Main {
public static void main(String[] args) {

// create the first set
Set<String> languages1 = new HashSet<>();
languages1.add(“Java”);
languages1.add(“Python”);
System.out.println(“Programming Languages: ” + languages1);

// create second set
Set<String> languages2 = new HashSet<>();
languages2.add(“English”);
languages2.add(“Spanish”);
System.out.println(“Human Language: ” + languages2);

Set<String> unionSet = Sets.union(languages1, languages2);
System.out.println(“Union is: ” + unionSet);
}
}



Leave a Reply

Your email address will not be published. Required fields are marked *