intersect All Collection of Sets - Java java.util

Java examples for java.util:Collection Intersect

Description

intersect All Collection of Sets

Demo Code


//package com.java2s;

import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;

import java.util.Set;

public class Main {
    public static void main(String[] argv) {
        Collection sets = java.util.Arrays.asList("asdf", "java2s.com");
        System.out.println(intersectAll(sets));
    }/*from   ww w.  jav a 2  s  .com*/

    public static <T> Set<T> intersectAll(Collection<Set<T>> sets) {
        if (sets.size() == 0)
            return Collections.emptySet();
        Set<T> intersection = null;
        for (Set<T> set : sets) {
            if (intersection == null)
                intersection = new HashSet<T>(set);
            else
                intersection.retainAll(set);
        }
        return intersection;
    }
}

Related Tutorials