Is there a cleaner way to check whether a value is present at a particular index like list.getOrDefault(index, "defaultValue")
. Or even do a default operation when the particular index is out of range of the list.
The normal way to do this is to check for size of the list before attempting this operation.
The getOrDefault(Object key, V defaultValue) method of Map interface, implemented by HashMap class is used to get the value mapped with specified key. If no value is mapped with the provided key then the default value is returned.
The List interface in Java provides a way to store the ordered collection. It is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements.
Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).
The default List
interface does not have this functionality. There is Iterables.get
in Guava:
Iterables.get(iterable, position, defaultValue);
Returns the element at the specified position in
iterable
ordefaultValue
ifiterable
contains fewer thanposition + 1
elements.Throws
IndexOutOfBoundsException
ifposition
is negative.
If this is functionality you intend to use a lot and can't afford to depend on third-party libraries, you could write your own static method (here inspired by the Guava Lists
class):
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With