Removes the first element from the given Iterable - Java java.util

Java examples for java.util:Iterable Element

Description

Removes the first element from the given Iterable

Demo Code

/*******************************************************************************
 * Copyright (c) 2014 Karlsruhe Institute of Technology, Germany
 *                    Technical University Darmstadt, Germany
 *                    Chalmers University of Technology, Sweden
 * 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://from  www  .  j a  v  a2  s. c om
 *    Technical University Darmstadt - initial API and implementation and/or initial documentation
 *******************************************************************************/
//package com.java2s;

import java.util.Iterator;

import java.util.NoSuchElementException;

public class Main {
    /**
     * Removes the first element from the given {@link Iterable}.
     * @param iterable The {@link Iterable} to remove first element from.
     * @return The removed first element or {@code null} if no element was removed.
     */
    public static <T> T removeFirst(Iterable<T> iterable) {
        try {
            if (iterable != null) {
                Iterator<T> iter = iterable.iterator();
                T next = iter.next();
                iter.remove();
                return next;
            } else {
                return null;
            }
        } catch (NoSuchElementException e) {
            return null; // Iterable must be empty.
        }
    }
}

Related Tutorials