Java Collection Null getItemAtPositionOrNull(Collection collection, int position)

Here you can find the source of getItemAtPositionOrNull(Collection collection, int position)

Description

Returns the n-th item or null if collection is smaller.

License

Open Source License

Parameter

Parameter Description
collection the given collection
position position of the wanted item

Exception

Parameter Description
NullPointerException if collection is null

Return

the item on position or null if the given collection is too small

Declaration

public static <T> T getItemAtPositionOrNull(Collection<T> collection, int position) 

Method Source Code

//package com.java2s;
/*//  w ww  . j  a  va2  s.c o m
 * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved.
 *
 * 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.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    /**
     * Returns the n-th item or {@code null} if collection is smaller.
     *
     * @param collection the given collection
     * @param position   position of the wanted item
     * @return the item on position or {@code null} if the given collection is too small
     * @throws NullPointerException if collection is {@code null}
     */
    public static <T> T getItemAtPositionOrNull(Collection<T> collection, int position) {
        if (position >= collection.size()) {
            return null;
        }
        if (collection instanceof List) {
            return ((List<T>) collection).get(position);
        }
        Iterator<T> iterator = collection.iterator();
        T item = null;
        for (int i = 0; i < position + 1; i++) {
            item = iterator.next();
        }
        return item;
    }
}

Related

  1. countNonNull(Collection dist)
  2. countNotNull(Collection collection)
  3. getNextNullIndex(C collection)
  4. getNumberOfNonNullElements(final Collection col)
  5. getSingleElementOrNull(Collection collection)
  6. getSizeNullSafe(final Collection collection)