Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 - get by index but something similar to 'getOrDefault' for Map?

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.

like image 510
FrailWords Avatar asked Jan 12 '17 07:01

FrailWords


People also ask

What does the getOrDefault () method on map do?

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.

What is List of () in Java?

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.

What is the default value of HashMap in Java?

Constructs an empty HashMap with the default initial capacity (16) and the default load factor (0.75).


1 Answers

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 or defaultValue if iterable contains fewer than position + 1 elements.

Throws IndexOutOfBoundsException if position 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;
  }

}
like image 105
Magnilex Avatar answered Oct 10 '22 01:10

Magnilex