Java Collection Flatten flatten(Collection original)

Here you can find the source of flatten(Collection original)

Description

flatten

License

Open Source License

Declaration

public static <T> Collection<T> flatten(Collection<T> original) 

Method Source Code

//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>();
    }
}

Related

  1. flatten(Collection l)
  2. flatten(Collection list, Class type)
  3. flatten(Collection> nestedList)
  4. flatten(Collection> collOfLists)
  5. flatten(Collection collection, char separator)
  6. flatten(final S targetCollection, final Collection> setOfSets)
  7. flattenCollection(Collection col)
  8. flattenCollection(Collection array, String fmt, char separator)
  9. flattenForest(Collection forest)