Java Collection Intersect intersection(Collection a, Collection b)

Here you can find the source of intersection(Collection a, Collection b)

Description

iterator over all elements contained in the intersection of the two collections

License

Open Source License

Parameter

Parameter Description
a a parameter
b a parameter

Return

intersection

Declaration

public static <T> Iterable<T> intersection(Collection<T> a, Collection<T> b) 

Method Source Code


//package com.java2s;
/*//w w w. j  av a 2 s.  c om
 * SetUtils.java Copyright (C) 2019. Daniel H. Huson
 *
 *  (Some files contain contributions from other authors, who are then mentioned separately.)
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.util.Collection;
import java.util.Iterator;

public class Main {
    /**
     * iterator over all elements contained in the intersection of the two collections
     *
     * @param a
     * @param b
     * @return intersection
     */
    public static <T> Iterable<T> intersection(Collection<T> a, Collection<T> b) {
        return () -> new Iterator<T>() {
            final Iterator<T> it = a.iterator();
            T v = null;

            {
                while (it.hasNext()) {
                    v = it.next();
                    if (b.contains(v))
                        break;
                }
            }

            @Override
            public boolean hasNext() {
                return v != null;
            }

            @Override
            public T next() {
                final T result = v;
                while (it.hasNext()) {
                    v = it.next();
                    if (b.contains(v))
                        break;
                }
                return result;
            }
        };
    }
}

Related

  1. intersection(Collection> availableValuesByDescriptor)
  2. intersection(Collection... collections)
  3. intersection(Collection> sets)
  4. intersection(Collection a, Collection b)
  5. intersection(Collection a, Collection b)
  6. intersection(Collection values1, Collection values2)
  7. intersection(final Collection a, final Collection b)
  8. intersection(final Collection c1, final Collection c2)
  9. intersection(final Collection a, final Collection b)