×

Union in Java

Sets.union() method in Java returns an immutable representation of both the union of two sets. Every element that is present in either backup set is included in the set that is returned. When iterating over all the returned sets, each member of set2 that is not also in set1 is iterated over after all of the elements from set1, in that order.

Syntax:

public static <E> 
  Sets.SetView<E> 
    union(Set<? extends E> set1, 
          Set<? extends E> set2)

Return Value: An unchangeable picture of the merging of two sets is what this method returns.

Example 1:

UnionExpl.java

// Guava's Sets.union() function 
// is demonstrated in Java
import com.google.common.collect.Sets;
import java.util.Set;
  
class UnionExpl1 {
  
    // Main code
    public static void main(String[] args)
    {
        // Creating the first set
        Set<Integer>
            s1 = Sets.newHashSet(1,2,3,4,5);
  
        // Creating the second set
        Set<Integer>
            s2 = Sets.newHashSet(3,5,7,9);
  
        // Using Guava's Sets.union() method
        Set<Integer>
            a = Sets.union(s1, s2);
  
        // Displaying the union of set set1 and set2
        System.out.println("Set 1: "
                           + s1);
        System.out.println("Set 2: "
                           + s2);
        System.out.println("Set 1 union Set 2: "
                           + a);
    }
}

Output:

Set 1: [1,2,3,4,5]
Set 2: [3,5,7,9]
Set 1 union Set 2: [1,2,3,4,5,7,9]

UnionExpl1.java

// Guava's Sets.union() function 
// is demonstrated in Java


  
import com.google.common.collect.Sets;
import java.util.Set;
  
class UnionExpl1 {
  
    // Main code
    public static void main(String[] args)
    {
        // Creating the first set
        Set<String>
            s1 = Sets.newHashSet("J", "a", "v", "a", "t");
  
        // Creating the second set
        Set<String>
            s2 = Sets.newHashSet("p", "o", "i", "n", "t");
  
        // Using Guava's Sets.union() method
        Set<String>
            a = Sets.union(s1, s2);
  
        // Displaying the union of set set1 and set2
        System.out.println("Set 1: "
                           + s1);
        System.out.println("Set 2: "
                           + s2);
        System.out.println("Set 1 union Set 2: "
                           + a);
    }
}

Output:

Set 1: [J,a,v,a,t]
Set 2: [p,o,i,n,t]
Set 1 union Set 2: [J,a,v,a,t,p,o,i,n,t]

Related Topics

Java Map Example

In Java, the Map is an interface that is used mainly to denote key and value pairs. The central concept and theme of this mapping in the java collection framework...

4 minutes read.

Java Pi

What is Pi? There are many formulas in geometry that employ the Pi constant to calculate things like circumference, area, and volume. A circle's circumference divided by its diameter yields a...

3 minutes read.

Crown Pattern in Java

We know the importance of solving pattern problems. We can solve pattern problems by using any programming language. There is no rule to translating into a particular programming language. We...

4 minutes read.

Java.sql.Time Format

In JDBC API as a cover aroundjava.util.Date that handles SQL-specific requirements we use the java.sql.Time. The java.sql.Time extends java.util.Date class. To represent SQL TIME, without a date this class is...

6 minutes read.

Java Anon Proxy

The Java Anon Proxy (JAP), also known as JonDonym, is a proxy system designed to enable Web browsing with revocable (the use of or publication under a pseudonym, a false...

4 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Applet Program in Java

Applet Program in Java An applet is a program that can be embedded in a web page. Applets programs are run by a web browser. It mainly works on the client-side....

3 minutes read.

Java StringBuffer vs StringBuilder

Java StringBuffer vs StringBuilder StringBuffer The StringBuffer class is used to create mutable string. StringBuffer shows writable and growable character sequences. Java StringBuffer program FileName: StringBufferExample.java // A basic program that demonstrates the working...

2 minutes read.

How to use Lambda Expression in Java?

The new and significant lambda expression feature of Java was added in Java SE 8. It provides a clear and concise mechanism for describing a single method interface using an...

4 minutes read.

Missing Number in an Arithmetic Progression in Java

Given an array that shows the elements of an orderly arithmetic progression. Find the missing number to complete the succession of elements. Example:  Input: a [ ] = {2 , 4 , 6...

3 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Java vs Scala

Java : Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say...

4 minutes read.

Compile time vs Runtime in java

Introduction: This article will discuss compile time vs. runtime in java. Compile time and runtime are two programming terms utilized in software improvement. Compile time is when the source code is...

3 minutes read.

Split String into String Array in Java

The String split() technique returns a variety of divided strings after the strategy parts the given String around matches of a given normal articulation containing the delimiters. The ordinary articulation...

4 minutes read.

Java Integer compareUnsigned() method

The compareUnsigned() method of Integer class compares two int objects numerically by treating the values as unsigned. Syntax public static int compareUnsigned(int x , int y) Parameters The parameters ‘x’ and ‘y’ represent the...

1 minute read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.