Languages
[Edit]
EN

Java Guava - Sets intersection, difference, union and symmetricDifference practical examples

7 points
Created by:
JustMike
28980

Guava - Sets intersection, difference, union practical example

import com.google.common.collect.Sets;

import java.util.LinkedHashSet;
import java.util.Set;

public class GuavaSetsExample__intersection_difference_union {

    public static void main(String[] args) {

        Set<String> set1 = new LinkedHashSet<>();
        set1.add("1"); // common
        set1.add("2"); // common
        set1.add("3"); // diff
        set1.add("4"); // diff

        Set<String> set2 = new LinkedHashSet<>();
        set2.add("1"); // common
        set2.add("2"); // common
        set2.add("5"); // diff
        set2.add("6"); // diff

        Sets.SetView<String> intersection = Sets.intersection(set1, set2);
        System.out.println("Intersection:");
        System.out.println(intersection); // [1, 2]

        Sets.SetView<String> diffBetween_Set1_Set2 = Sets.difference(set1, set2);
        System.out.println("Diff between set1 and set2:");
        System.out.println(diffBetween_Set1_Set2); // [3, 4]

        Sets.SetView<String> diffBetween_Set2_Set1 = Sets.difference(set2, set1);
        System.out.println("Diff between set2 and set1:");
        System.out.println(diffBetween_Set2_Set1); // [5, 6]

        Sets.SetView<String> union = Sets.union(set1, set2);
        System.out.println("Union:");
        System.out.println(union); // [1, 2, 3, 4, 5, 6]
    }
}

Guava - Sets.symmetricDifference practical example

import java.util.LinkedHashSet;
import java.util.Set;

public class GuavaSetsExample__symmetricDifference {

    public static void main(String[] args) {

        Set<String> set1 = new LinkedHashSet<>();
        set1.add("1"); // common
        set1.add("2"); // common
        set1.add("3"); // diff
        set1.add("4"); // diff

        Set<String> set2 = new LinkedHashSet<>();
        set2.add("1"); // common
        set2.add("2"); // common
        set2.add("5"); // diff
        set2.add("6"); // diff

        Sets.SetView<String> symmetricDifference1 = Sets.symmetricDifference(set1, set2);
        System.out.println("symmetricDifference1");
        System.out.println(symmetricDifference1); // [3, 4, 5, 6]

        Sets.SetView<String> symmetricDifference2 = Sets.symmetricDifference(set2, set1);
        System.out.println("symmetricDifference2");
        System.out.println(symmetricDifference2); // [5, 6, 3, 4]
    }
}

 

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