Java tutorial
//package com.java2s; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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; public class Main { /** * Given two Collections, return the size of their union * @param firstCollection The first collection. <code>null</code> is allowed. * @param secondCollection The second collection. <code>null</code> is allowed. * @return */ public static <E> int getUnionSize(Collection<? extends E> firstCollection, Collection<? extends E> secondCollection) { int firstSize = (firstCollection != null) ? firstCollection.size() : 0; int secondSize = (secondCollection != null) ? secondCollection.size() : 0; if (firstSize == 0) return secondSize; if (secondSize == 0) return firstSize; // determine the size of the union by iterating over the smaller collection int size; Collection<? extends E> iteratingCollection; Collection<? extends E> baseCollection; if (firstSize >= secondSize) { baseCollection = firstCollection; iteratingCollection = secondCollection; size = firstSize; } else { baseCollection = secondCollection; iteratingCollection = firstCollection; size = secondSize; } for (E currValue : iteratingCollection) { if (!baseCollection.contains(currValue)) { size++; } } return size; } }