Java examples for Collection Framework:Array Element Filter
Returns a new ArrayList with the same contents as source, except for the case that source is nil or empty, in which source itself is returned.
/******************************************************************************* * Copyright (c) 2010 SAP AG.//www . j av a 2 s. c o m * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Emil Simeonov - initial API and implementation. * Dimitar Donchev - initial API and implementation. * Dimitar Tenev - initial API and implementation. * Nevena Manova - initial API and implementation. * Georgi Konstantinov - initial API and implementation. * Jakob Spies - initial API and implementation. *******************************************************************************/ //package com.java2s; import java.util.ArrayList; import java.util.Collection; public class Main { public static void main(String[] argv) { Collection source = java.util.Arrays.asList("asdf", "java2s.com"); System.out.println(duplicate(source)); } /** * Returns a new {@link ArrayList} with the same contents as <code>source</code>, * except for the case that <code>source</code> is nil or empty, in which <code>source</code> * itself is returned. * @param <T> element type * @param source the {@link Collection} to clone * @return a new {@link ArrayList} with the same contents as <code>source</code>, * except for the case that <code>source</code> is nil or empty, in which <code>source</code> * itself is returned */ public static <T> Collection<T> duplicate(Collection<T> source) { final Collection<T> result; if (source == null || source.isEmpty()) { result = source; } else { result = new ArrayList<T>(source.size()); result.addAll(source); } return result; } }