Let's assume that you have a List<String> strings
that you want the first item from.
There are several ways to do that:
Java (pre-8):
String firstElement = null;
if (!strings.isEmpty() && strings.size() > 0) {
firstElement = strings.get(0);
}
Java 8:
Optional<String> firstElement = strings.stream().findFirst();
Guava
String firstElement = Iterables.getFirst(strings, null);
Apache commons (4+)
String firstElement = (String) IteratorUtils.get(strings, 0);
Apache commons (before 4)
String firstElement = (String) CollectionUtils.get(strings, 0);
Followed by or encapsulated within the appropriate checks or try-catch blocks.
Kotlin:
In Kotlin both Arrays and most of the Collections (eg: List) have a first
method call.
So your code would look something like this
for a List:
val stringsList: List<String?> = listOf("a", "b", null)
val first: String? = stringsList.first()
for an Array:
val stringArray: Array<String?> = arrayOf("a", "b", null)
val first: String? = stringArray.first()
Followed by or encapsulated within the appropriate checks or try-catch blocks.
Kotlin also includes safer ways to do that for kotlin.collections
, for example firstOrNull or getOrElse, or getOrDefault when using JRE8