Skip to content

Changes in first() and single() implementations #8

@brunovinicius

Description

@brunovinicius

Current first() and single() implementations are not enough.
We need extra overloads that cove a wider variety of use cases.

Current implementations of first() and single() shall retain behavior but will now be called firstOrNull() and singleOrNull().

New implementations of single() and first() will throw NoSuchElement exception if no item is found.

Additionally a new singleOrDefault(T) and firstOrDefault(T) overloads will return the value expecified by the developer in case no item is found.

Here is sample code courtesy of @sergiotaborda

public T first(){
   return iterator().next();
}

public T firstOrNull(){
   return firstOrValue(null);
}

public T firstOrValue(T value){
   Iterator<T> it = iterator();
   return it.hasNext() ? value: it.next();
}

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions