集册 Java实例教程 列表列表的并集

列表列表的并集

欢马劈雪     最近更新时间:2020-01-02 10:19:05

443
列表的并集

/*

 * Copyright (C) 2013

 *

 * 52?North Initiative for Geospatial Open Source Software GmbH

 * Contact: Andreas Wytzisk

 * Martin-Luther-King-Weg 24

 * 48155 Muenster, Germany

 * info@52north.org

 *

 * 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

 */

//package com.nowjava;// 来 自 时代Java

import java.util.ArrayList;


import java.util.Collection;

import java.util.Collections;


import java.util.HashSet;

import java.util.LinkedList;

import java.util.List;

import java.util.Map;


import java.util.Set;


public class Main {

    public static void main(String[] argv) {

        Collection collectionOfCollection = java.util.Arrays.asList("asdf",

                "nowjava.com");

        System.out.println(unionOfListOfLists(collectionOfCollection));/** 来自 n o w  j a v a  . c o m**/

    }


    /**

     * @param collectionOfCollection

     *            a Collection<Collection<T>>

     * 

     * @return a Set<T> containing all values of all Collections<T>

     *         without any duplicates

     */

    public static <T> Set<T> unionOfListOfLists(

            final Collection<? extends Collection<T>> collectionOfCollection) {

        if (collectionOfCollection == null

                || collectionOfCollection.isEmpty()) {

            return new HashSet<T>(0);

        }

        final HashSet<T> union = new HashSet<T>();

        for (final Collection<T> col : collectionOfCollection) {

            if (col != null) {

                for (final T t : col) {

                    if (t != null) {

                        union.add(t);

                    }

                }

            }

        }

        return union;

    }


    public static <T> List<T> asList(final Iterable<? extends T> iterable) {

        return (iterable instanceof Collection) ? new LinkedList<T>(

                (Collection<? extends T>) iterable) : new LinkedList<T>() {

            private static final long serialVersionUID = 3109256773218160485L;

            {

                if (iterable != null) {

                    for (final T t : iterable) {

                        add(t);

                    }

                }

            }

        };

    }


    public static <T> List<T> asList(final T t, final T... ts) {

        final ArrayList<T> list = new ArrayList<T>(ts.length + 1);

        list.add(t);

        Collections.addAll(list, ts);

        return list;

    }


    /**

     * Check if collection is not <tt>null</tt> and empty

     * 

     * @param collection

     *          Collection to check

     * 

     * @return <tt>true</tt>, if collection is not null and empty, else <tt>false</tt>

     */

    
展开阅读全文