Magento – Magento 2 Get last and first item from model collections

collection;magento-2.1resource-model

I want to retrieve the last and first item from model collection in magento 2, in magento 1.9 i can simply retrieve it like this :

$lastItem = $collections->getLastItem();
$firstItem = $collections->getFirstItem();

is there a way i can do the same in magento 2, without using foreach loop like this:

$collections = $this->_objectManager->create('Namespace\Module\Model\Test')->getCollection(); 
$i=0;
foreach($collections as $collection){
  if($i == 0){
    $firstItem = $collection;
    $i++;
  } else{
    $lastItem = $collection;
  }
}

Best Answer

This is Tested Solution feel free to implement

$firstItem = $collections->getFirstItem();
$lastItem = $collections->getLastItem();

echo 'This First Record in Collection <br> ';

print_r($firstItem->getData());

echo '<br> This LastRecord in Collection <br> ';

print_r($lastItem->getData());