我使用micro-util类获取列表的最后一个(和第一个)元素:
public final class Lists {
private Lists() {
}
public static T getFirst(List list) {
return list != null && !list.isEmpty() ? list.get(0) : null;
}
public static T getLast(List list) {
return list != null && !list.isEmpty() ? list.get(list.size() - 1) : null;
}
}
稍微灵活一些:
import java.util.List;
/**
* Convenience class that provides a clearer API for obtaining list elements.
*/
public final class Lists {
private Lists() {
}
/**
* Returns the first item in the given list, or null if not found.
*
* @param The generic list type.
* @param list The list that may have a first item.
*
* @return null if the list is null or there is no first item.
*/
public static T getFirst( final List list ) {
return getFirst( list, null );
}
/**
* Returns the last item in the given list, or null if not found.
*
* @param The generic list type.
* @param list The list that may have a last item.
*
* @return null if the list is null or there is no last item.
*/
public static T getLast( final List list ) {
return getLast( list, null );
}
/**
* Returns the first item in the given list, or t if not found.
*
* @param The generic list type.
* @param list The list that may have a first item.
* @param t The default return value.
*
* @return null if the list is null or there is no first item.
*/
public static T getFirst( final List list, final T t ) {
return isEmpty( list ) ? t : list.get( 0 );
}
/**
* Returns the last item in the given list, or t if not found.
*
* @param The generic list type.
* @param list The list that may have a last item.
* @param t The default return value.
*
* @return null if the list is null or there is no last item.
*/
public static T getLast( final List list, final T t ) {
return isEmpty( list ) ? t : list.get( list.size() - 1 );
}
/**
* Returns true if the given list is null or empty.
*
* @param The generic list type.
* @param list The list that has a last item.
*
* @return true The list is empty.
*/
public static boolean isEmpty( final List list ) {
return list == null || list.isEmpty();
}
}