Java Iterable First getFirst(Iterable iterable)

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

Description

Return the first element in the given (non-empty) Iterable

License

Open Source License

Exception

Parameter Description
NoSuchElementException if the iterable is empty

Declaration

public static <T> T getFirst(Iterable<? extends T> iterable) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.List;

import java.util.NoSuchElementException;

public class Main {
    /**//from ww  w. j ava2  s  .co  m
     * Return the first element in the given (non-empty) {@link Iterable}
     * @throws NoSuchElementException if the iterable is empty
     */
    public static <T> T getFirst(Iterable<? extends T> iterable) {
        if (iterable instanceof List) {
            final List<T> list = (List<T>) iterable;
            if (list.isEmpty())
                throw new NoSuchElementException();
            return list.get(0);
        } else {
            return iterable.iterator().next();
        }
    }
}

Related

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