gpt4 book ai didi

collections - Java8 - 按索引获取,但类似于 Map 的 'getOrDefault'?

转载 作者:行者123 更新时间:2023-12-03 21:28:56 26 4
gpt4 key购买 nike

是否有更简洁的方法来检查特定索引处是否存在值,例如 list.getOrDefault(index, "defaultValue") .或者甚至在特定索引超出列表范围时执行默认操作。

执行此操作的正常方法是在尝试此操作之前检查列表的大小。

最佳答案

默认 List 界面没有这个功能。有Iterables.getGuava :

Iterables.get(iterable, position, defaultValue);

Returns the element at the specified position in iterable ordefaultValue if iterable contains fewer than position + 1 elements.

Throws IndexOutOfBoundsException if position is negative.


如果这是您打算大量使用的功能并且不能依赖第三方库,您可以编写自己的静态方法(此处受 Guava Lists 类的启发):
public class Lists {

public static <E> E getOrDefault(int index, E defaultValue, List<E> list) {
if (index < 0) {
throw new IllegalArgumentException("index is less than 0: " + index);
}
return index <= list.size() - 1 ? list.get(index) : defaultValue;
}

}

关于collections - Java8 - 按索引获取,但类似于 Map 的 'getOrDefault'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41607657/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com