Java Iterable First firstElement(Iterable iterable)

Here you can find the source of firstElement(Iterable iterable)

Description

Returns the first element of the given Iterable

License

Apache License

Parameter

Parameter Description
iterable a parameter

Declaration

public static <E> E firstElement(Iterable<E> iterable) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright 2011 Danny Kunz//from   w w w. j  a  v  a  2s .  com
 * 
 * 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.
 ******************************************************************************/

import java.util.Iterator;

public class Main {
    /**
     * Returns the first element of the given {@link Iterable}
     * 
     * @param iterable
     * @return
     */
    public static <E> E firstElement(Iterable<E> iterable) {
        //
        final int indexPosition = 0;
        return elementAt(iterable, indexPosition);
    }

    /**
     * Returns the element of the given {@link Iterable} at the given index position. Does never throw an {@link Exception} instead
     * returns null if no element could be resolved.
     * 
     * @param iterable
     * @param indexPosition
     * @return
     */
    public static <E> E elementAt(final Iterable<E> iterable, final int indexPosition) {
        //
        E retval = null;

        //
        if (iterable != null) {
            //
            final Iterator<E> iterator = iterable.iterator();
            if (iterator != null) {
                for (int ii = 0; ii <= indexPosition && iterator.hasNext(); ii++) {
                    //
                    final E nextElement = iterator.next();
                    if (ii == indexPosition) {
                        retval = nextElement;
                    }
                }
            }
        }

        //
        return retval;
    }
}

Related

  1. first(final Iterable iter)
  2. first(Iterable iterable)
  3. first(Iterable i)
  4. first(Iterable iterable)
  5. first(Iterable iterable)
  6. firstElementOrNull(Iterable iterable)
  7. firstOf(final Iterable iterable)
  8. firstOrNull(Iterable iterable)
  9. getFirst(final Iterable iterable)