Java tutorial
//package com.java2s; /* * 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; } }