Here you can find the source of flatten(Collection
public static <T> Collection<T> flatten(Collection<T> original)
//package com.java2s; /******************************************************************************* * Copyright (c) 2008 The University of York. * 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 * /*w w w .j av a2 s . c o m*/ * Contributors: * Dimitrios Kolovos - initial API and implementation ******************************************************************************/ import java.util.ArrayList; import java.util.Collection; import java.util.List; public class Main { public static <T> Collection<T> flatten(Collection<T> original) { // First see if there are no nested collections // and in this case just return this boolean hasNested = false; for (Object o : original) { if (o instanceof Collection) { hasNested = true; break; } } if (!hasNested) return original; // If there are nested collections Collection<T> flattened = createDefaultList(); for (T next : original) { if (next instanceof Collection) { flattened.addAll(flatten((Collection<T>) next)); } else { flattened.add(next); } } return flattened; } public static <T> List<T> createDefaultList() { return new ArrayList<T>(); } }