Here you can find the source of first(final Iterable
Parameter | Description |
---|---|
T | a parameter |
iter | a parameter |
null
otherwise
public static <T> T first(final Iterable<T> iter)
//package com.java2s; /**//from w w w . ja v a 2s . c o m * Copyright 2010 Molindo GmbH * * 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; import java.util.NoSuchElementException; public class Main { public static final Iterator<?> EMPTY_ITERATOR = new Iterator<Object>() { @Override public boolean hasNext() { return false; } @Override public Object next() { throw new NoSuchElementException(); } @Override public void remove() { throw new IllegalStateException(); } }; /** * * @param <T> * @param iter * @return the first element if available, <code>null</code> otherwise */ public static <T> T first(final Iterable<T> iter) { return iter == null ? null : next(iter.iterator()); } /** * * @param <T> * @param iter * @return the next element if available, <code>null</code> otherwise */ public static <T> T next(final Iterator<T> iter) { return iter == null || !iter.hasNext() ? null : iter.next(); } /** * @param <T> * @param iterable * @return {@link Iterable#iterator()} or {@link #EMPTY_ITERATOR} if null */ @SuppressWarnings("unchecked") public static <T> Iterator<T> iterator(Iterable<T> iterable) { return iterable == null ? (Iterator<T>) EMPTY_ITERATOR : iterable.iterator(); } }