Here you can find the source of intersection(Set
Parameter | Description |
---|---|
T | the generic type |
setA | the set a |
setB | the set b |
public static <T> Set<T> intersection(Set<T> setA, Set<T> setB)
//package com.java2s; /*//www.j ava 2 s.co m Copyright 2014 Array-Utilities Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * */ import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Set; public class Main { /** * Intersection. * * @param <T> the generic type * @param setA the set a * @param setB the set b * @return the sets the */ public static <T> Set<T> intersection(Set<T> setA, Set<T> setB) { // SetA empty & SetB has values if (isEmpty(setA) && !isEmpty(setB)) { return Collections.unmodifiableSet(new LinkedHashSet<T>()); } // SetA has values & SetB is empty if (!isEmpty(setA) && isEmpty(setB)) { return Collections.unmodifiableSet(new LinkedHashSet<T>()); } // Both set are empty if (isEmpty(setA) && isEmpty(setB)) { return Collections.unmodifiableSet(new LinkedHashSet<T>()); } if (setA.equals(setB)) { return setA; } Set<T> setC = new LinkedHashSet<T>(); Iterator<T> iterA = setA.iterator(); while (iterA.hasNext()) { T obj = iterA.next(); if (setB.contains(obj)) { setC.add(obj); } } return Collections.unmodifiableSet(setC); } /** * Checks if is empty. * * @param <E> * the element type * @param collection * the collection * @return true, if is empty */ public static <E> boolean isEmpty(Collection<? super E> collection) { if ((collection.size() == 0) || (collection == null)) return true; return false; } }