Java Iterable First getFirstOrNull(Iterable iterable)

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

Description

Get the first element from iterable.

License

Apache License

Parameter

Parameter Description
iterable to find the first element.
T type of the element.

Return

the element iff there is one or more, null if there is none.

Declaration

public static <T> T getFirstOrNull(Iterable<T> iterable) 

Method Source Code

//package com.java2s;
/*//from  www  .ja va 2  s  .c om
 * Copyright (c)  [2011-2016] "Pivotal Software, Inc." / "Neo Technology" / "Graph Aware Ltd."
 *
 * This product is licensed to you under the Apache License, Version 2.0 (the "License").
 * You may not use this product except in compliance with the License.
 *
 * This product may include a number of subcomponents with
 * separate copyright notices and license terms. Your use of the source
 * code for these subcomponents is subject to the terms and
 * conditions of the subcomponent's license, as noted in the LICENSE file.
 *
 */

import java.util.Iterator;

public class Main {
    /**
     * Get the first element from iterator.
     *
     * @param iterator to find the first element.
     * @param <T>      type of the element.
     * @return the element iff there is one or more, null if there is none.
     */
    public static <T> T getFirstOrNull(Iterator<T> iterator) {
        T result = null;

        if (iterator.hasNext()) {
            result = iterator.next();
        }

        return result;
    }

    /**
     * Get the first element from iterable.
     *
     * @param iterable to find the first element.
     * @param <T>      type of the element.
     * @return the element iff there is one or more, null if there is none.
     */
    public static <T> T getFirstOrNull(Iterable<T> iterable) {
        return getFirstOrNull(iterable.iterator());
    }
}

Related

  1. getFirst(Iterable iterable)
  2. getFirst(Iterable iterable)
  3. getFirst(Iterable iterable, T defaultValue)
  4. getFirstElement(Object maybeIterable)
  5. getFirstOrNull(Iterable it)
  6. removeFirst(Iterable iterable)