Here you can find the source of getItemAtPositionOrNull(Collection
Parameter | Description |
---|---|
collection | the given collection |
position | position of the wanted item |
Parameter | Description |
---|---|
NullPointerException | if collection is null |
public static <T> T getItemAtPositionOrNull(Collection<T> collection, int position)
//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; } }