Java tutorial
//package com.java2s; /* * Lightmare, Lightweight embedded EJB container (works for stateless session beans) with JPA / Hibernate support * * Copyright (c) 2013, Levan Tsinadze, or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; public class Main { public static final int FIRST_INDEX = 0; public static final int EMPTY_ARRAY_LENGTH = 0; /** * Peaks first element from collection * * @param collection * @return T */ public static <T> T getFirst(Collection<T> collection) { T value; if (valid(collection)) { if (collection instanceof List) { value = getFirstFromList(((List<T>) collection)); } else { Iterator<T> iterator = collection.iterator(); value = iterator.next(); } } else { value = null; } return value; } /** * Peaks first element from array * * @param collection * @return T */ public static <T> T getFirst(T[] values) { T value; if (valid(values)) { value = values[FIRST_INDEX]; } else { value = null; } return value; } /** * Checks passed {@link Collection} instance on null and on emptiness * returns true if it is not null and is not empty * * @param collection * @return <code></code> */ public static boolean valid(Collection<?> collection) { return (collection != null && !collection.isEmpty()); } /** * Checks passed {@link Map} instance on null and emptiness returns true if * it is not null and is not empty * * @param map * @return <code>boolean</code> */ public static boolean valid(Map<?, ?> map) { return (map != null && !map.isEmpty()); } /** * Checks if passed array of {@link Object}'s instances is not null and is * not empty * * @param array * @return <code>boolean</code> */ public static boolean valid(Object[] array) { return (array != null && array.length > EMPTY_ARRAY_LENGTH); } /** * Peaks first element from list * * @param list * @return T */ private static <T> T getFirstFromList(List<T> list) { T value; if (valid(list)) { value = list.get(FIRST_INDEX); } else { value = null; } return value; } }