Joh*_*itb 639
以下是List接口的一部分(ArrayList实现):
E e = list.get(list.size() - 1);
Run Code Online (Sandbox Code Playgroud)
E是元素类型.如果列表为空,则get抛出一个IndexOutOfBoundsException.您可以在此处找到完整的API文档.
Ant*_*bbs 198
在香草Java中没有一种优雅的方式.
在谷歌番石榴库是伟大的-看看他们的Iterables阶级.NoSuchElementException如果列表为空,此方法将抛出一个,而不是IndexOutOfBoundsException像典型size()-1方法那样 - 我发现NoSuchElementException更好,或者指定默认值的能力:
lastElement = Iterables.getLast(iterableList);
Run Code Online (Sandbox Code Playgroud)
如果列表为空,您还可以提供默认值,而不是例外:
lastElement = Iterables.getLast(iterableList, null);
Run Code Online (Sandbox Code Playgroud)
或者,如果您使用选项:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
Run Code Online (Sandbox Code Playgroud)
Hen*_*aul 185
这应该这样做:
if (arrayList != null && !arrayList.isEmpty()) {
T item = arrayList.get(arrayList.size()-1);
}
Run Code Online (Sandbox Code Playgroud)
use*_*153 27
我使用micro-util类来获取列表的最后一个(和第一个)元素:
public final class Lists {
private Lists() {
}
public static <T> T getFirst(List<T> list) {
return list != null && !list.isEmpty() ? list.get(0) : null;
}
public static <T> T getLast(List<T> list) {
return list != null && !list.isEmpty() ? list.get(list.size() - 1) : null;
}
}
Run Code Online (Sandbox Code Playgroud)
稍微灵活一点:
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 <T> 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> T getFirst( final List<T> list ) {
return getFirst( list, null );
}
/**
* Returns the last item in the given list, or null if not found.
*
* @param <T> 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> T getLast( final List<T> list ) {
return getLast( list, null );
}
/**
* Returns the first item in the given list, or t if not found.
*
* @param <T> 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> T getFirst( final List<T> 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 <T> 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> T getLast( final List<T> list, final T t ) {
return isEmpty( list ) ? t : list.get( list.size() - 1 );
}
/**
* Returns true if the given list is null or empty.
*
* @param <T> The generic list type.
* @param list The list that has a last item.
*
* @return true The list is empty.
*/
public static <T> boolean isEmpty( final List<T> list ) {
return list == null || list.isEmpty();
}
}
Run Code Online (Sandbox Code Playgroud)
M. *_*tin 13
List#getLastgetLast从Java 21开始,可以使用list的方法。这将返回列表的最后一项,NoSuchElementException如果列表为空则抛出 a 。
list.getLast();
Run Code Online (Sandbox Code Playgroud)
Ken*_*aul 10
该size()方法返回ArrayList中的元素数.元素的索引值是0通过的(size()-1),因此您将使用它myArrayList.get(myArrayList.size()-1)来检索最后一个元素.
在 Java 中没有优雅的方法来获取列表的最后一个元素(与例如items[-1]在 Python 中相比)。
你必须使用list.get(list.size()-1).
处理通过复杂方法调用获得的列表时,解决方法在于临时变量:
List<E> list = someObject.someMethod(someArgument, anotherObject.anotherMethod());
return list.get(list.size()-1);
Run Code Online (Sandbox Code Playgroud)
这是避免丑陋且通常昂贵甚至无法工作的版本的唯一选择:
return someObject.someMethod(someArgument, anotherObject.anotherMethod()).get(
someObject.someMethod(someArgument, anotherObject.anotherMethod()).size() - 1
);
Run Code Online (Sandbox Code Playgroud)
如果将此设计缺陷的修复引入 Java API,那就太好了。
正如解决方案中所述,如果为空,则抛出Listan 。IndexOutOfBoundsException更好的解决方案是使用以下Optional类型:
public class ListUtils {
public static <T> Optional<T> last(List<T> list) {
return list.isEmpty() ? Optional.empty() : Optional.of(list.get(list.size() - 1));
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所期望的,列表的最后一个元素以以下形式返回Optional:
var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;
Run Code Online (Sandbox Code Playgroud)
它还可以优雅地处理空列表:
var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;
Run Code Online (Sandbox Code Playgroud)
如果您有 Spring 项目,您还可以使用CollectionUtils.lastElementSpring ( javadoc ),因此您不需要像 Google Guava 那样添加额外的依赖项。
它是 null 安全的,因此如果您传递 null,您将仅收到 null 作为返回。但处理响应时要小心。
以下是一些单元测试来演示它们:
@Test
void lastElementOfList() {
var names = List.of("John", "Jane");
var lastName = CollectionUtils.lastElement(names);
then(lastName)
.as("Expected Jane to be the last name in the list")
.isEqualTo("Jane");
}
@Test
void lastElementOfSet() {
var names = new TreeSet<>(Set.of("Jane", "John", "James"));
var lastName = CollectionUtils.lastElement(names);
then(lastName)
.as("Expected John to be the last name in the list")
.isEqualTo("John");
}
Run Code Online (Sandbox Code Playgroud)
注意:org.assertj.core.api.BDDAssertions#then(java.lang.String)用于断言。
小智 5
使用lambdas:
Function<ArrayList<T>, T> getLast = a -> a.get(a.size() - 1);
Run Code Online (Sandbox Code Playgroud)
如果您使用 LinkedList ,则可以仅使用getFirst()and访问第一个元素和最后一个元素getLast()(如果您想要比 size() -1 和 get(0) 更简洁的方式)
声明一个链表
LinkedList<Object> mLinkedList = new LinkedList<>();
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用这些方法来获取所需的内容,在本例中,我们讨论的是列表的第一个和最后一个元素
/**
* Returns the first element in this list.
*
* @return the first element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return f.item;
}
/**
* Returns the last element in this list.
*
* @return the last element in this list
* @throws NoSuchElementException if this list is empty
*/
public E getLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return l.item;
}
/**
* Removes and returns the first element from this list.
*
* @return the first element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeFirst() {
final Node<E> f = first;
if (f == null)
throw new NoSuchElementException();
return unlinkFirst(f);
}
/**
* Removes and returns the last element from this list.
*
* @return the last element from this list
* @throws NoSuchElementException if this list is empty
*/
public E removeLast() {
final Node<E> l = last;
if (l == null)
throw new NoSuchElementException();
return unlinkLast(l);
}
/**
* Inserts the specified element at the beginning of this list.
*
* @param e the element to add
*/
public void addFirst(E e) {
linkFirst(e);
}
/**
* Appends the specified element to the end of this list.
*
* <p>This method is equivalent to {@link #add}.
*
* @param e the element to add
*/
public void addLast(E e) {
linkLast(e);
}
Run Code Online (Sandbox Code Playgroud)
那么,那么你可以使用
mLinkedList.getLast();
Run Code Online (Sandbox Code Playgroud)
获取列表的最后一个元素。
| 归档时间: |
|
| 查看次数: |
653055 次 |
| 最近记录: |