Populates the given collection by replacing any existing contents with the given elements, in a null-safe way. - Java java.util

Java examples for java.util:Collection Null Element

Description

Populates the given collection by replacing any existing contents with the given elements, in a null-safe way.

Demo Code

/*/*from w  ww .  ja  v a  2s .  com*/
 * Copyright 2002-2008 the original author or authors.
 * 
 * Licensed 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.
 */
//package com.book2s;

import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "book2s.com");
        Collection items = java.util.Arrays.asList("asdf", "book2s.com");
        System.out.println(populate(collection, items));
    }

    /**
     * Populates the given collection by replacing any existing contents with
     * the given elements, in a null-safe way.
     * 
     * @param <T> the type of element in the collection
     * @param collection the collection to populate (can be <code>null</code>)
     * @param items the items with which to populate the collection (can be
     *            <code>null</code> or empty for none)
     * @return the given collection (useful if it was anonymous)
     */
    public static <T> Collection<T> populate(
            final Collection<T> collection,
            final Collection<? extends T> items) {
        if (collection != null) {
            collection.clear();
            if (items != null) {
                collection.addAll(items);
            }
        }
        return collection;
    }
}

Related Tutorials