Author: tchemit Date: 2012-10-29 17:30:56 +0100 (Mon, 29 Oct 2012) New Revision: 2433 Url: http://nuiton.org/repositories/revision/nuiton-utils/2433 Log: refs #2386: Add get method in CollectionUtil (add getOrNull methods Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java Modified: trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java =================================================================== --- trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java 2012-10-29 16:13:42 UTC (rev 2432) +++ trunk/nuiton-utils/src/main/java/org/nuiton/util/CollectionUtil.java 2012-10-29 16:30:56 UTC (rev 2433) @@ -166,6 +166,31 @@ } /** + * Get data at given {@code index} from the given collection or + * {@code null} if no element at given position. + * + * @param collection the collection to scan + * @param index index to seek + * @param <T> type of data in collection + * @return the data found at given index, or {@code null} if not found + * @since 2.6.4 + */ + public static <T> T getOrNull(Collection<T> collection, int index) { + T result = null; + if (collection != null) { + int i = 0; + for (T t : collection) { + if (index == i) { + result = t; + break; + } + i++; + } + } + return result; + } + + /** * Get data at given {@code index} from the given collection. * * @param collection the collection to scan @@ -213,6 +238,26 @@ } return result; } + + /** + * Get data at given {@code index} from the given list or {@code null} if + * no such index in list. + * + * @param list the list to scan + * @param index index to seek + * @param <T> type of data in collection + * @return the data found at given index or {@code null} if no such index in list + * @since 2.6.4 + */ + public static <T> T getOrNull(List<T> list, int index) { + T result = null; + if (list != null) { + if (index <= list.size()) { + result = list.get(index); + } + } + return result; + } }