Java Collection Intersect intersection(Collection values1, Collection values2)

Here you can find the source of intersection(Collection values1, Collection values2)

Description

intersection

License

EUPL

Parameter

Parameter Description
values1 to intersect with values2
values2 to intersect with values1
T type

Return

the intersection of values1 and values2 with unique values ordered by values1

Declaration

public static <T> List<T> intersection(Collection<T> values1, Collection<T> values2) 

Method Source Code


//package com.java2s;
/*/*  ww  w.  j  av  a 2 s .com*/
 * Copyright (c) 2013 The Finnish National Board of Education - Opetushallitus
 *
 * This program is free software: Licensed under the EUPL, Version 1.1 or - as
 * soon as they will be approved by the European Commission - subsequent versions
 * of the EUPL (the "Licence");
 *
 * You may not use this work except in compliance with the Licence.
 * You may obtain a copy of the Licence at: http://www.osor.eu/eupl/
 *
 * 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
 * European Union Public Licence for more details.
 */

import java.util.*;

public class Main {
    /**
     * @param values1 to intersect with values2
     * @param values2 to intersect with values1
     * @param <T> type
     * @return the intersection of values1 and values2 with unique values ordered by values1
     */
    public static <T> List<T> intersection(Collection<T> values1, Collection<T> values2) {
        Set<T> added = new HashSet<T>(), set2 = new HashSet<T>(values2);
        List<T> results = new ArrayList<T>();
        for (T value : values1) {
            if (set2.contains(value) && !added.contains(value)) {
                results.add(value);
                added.add(value);
            }
        }
        return results;
    }
}

Related

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