如何获取数组列表的最后一个值?
当前回答
获取数组列表的最后一个值:
var yourlist = ["1","2","3"];
var lastvalue = yourlist[yourlist.length -1];
它给出的输出是3。
其他回答
如解决方案中所述,如果List为空,则抛出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));
}
}
如你所料,列表的最后一个元素作为Optional返回:
var list = List.of(10, 20, 30);
assert ListUtils.last(list).orElse(-1) == 30;
它还可以优雅地处理空列表:
var emptyList = List.<Integer>of();
assert ListUtils.last(emptyList).orElse(-1) == -1;
在普通Java中没有优雅的方法。
谷歌番石榴
谷歌番石榴库是伟大的-检查他们的Iterables类。如果列表为空,这个方法将抛出NoSuchElementException,而不是IndexOutOfBoundsException,就像典型的size()-1方法一样-我发现NoSuchElementException更好,或者能够指定默认值:
lastElement = Iterables.getLast(iterableList);
如果列表为空,你也可以提供一个默认值,而不是一个异常:
lastElement = Iterables.getLast(iterableList, null);
或者,如果你使用选项:
lastElementRaw = Iterables.getLast(iterableList, null);
lastElement = (lastElementRaw == null) ? Option.none() : Option.some(lastElementRaw);
这个怎么样? 在你班上的某个地方……
List<E> list = new ArrayList<E>();
private int i = -1;
public void addObjToList(E elt){
i++;
list.add(elt);
}
public E getObjFromList(){
if(i == -1){
//If list is empty handle the way you would like to... I am returning a null object
return null; // or throw an exception
}
E object = list.get(i);
list.remove(i); //Optional - makes list work like a stack
i--; //Optional - makes list work like a stack
return object;
}
这应该做到:
if (arrayList != null && !arrayList.isEmpty()) {
T item = arrayList.get(arrayList.size()-1);
}
如果您有一个Spring项目,您也可以使用CollectionUtils。因此,您不需要添加额外的依赖项,如谷歌Guava。
它是空安全的,所以如果你传递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");
}
注意:org.assertj.core.api.BDDAssertions#then(java.lang.String)用于断言。
推荐文章
- Intellij IDEA Java类在保存时不能自动编译
- 何时使用Mockito.verify()?
- 在maven中安装mvn到底做什么
- 不可变与不可修改的集合
- 如何在JSON中使用杰克逊更改字段名
- GSON -日期格式
- 如何从线程捕获异常
- 无法解析主机"<URL here>"没有与主机名关联的地址
- 如何在Java中打印二叉树图?
- String.format()在Java中格式化双重格式
- com.jcraft.jsch.JSchException: UnknownHostKey
- Java中的操作符重载
- 如何加速gwt编译器?
- 在Hibernate中重新连接分离对象的正确方法是什么?
- 应该……接住环内还是环外?