In this post I am going to explain how to get list of all customers or you can say customer collection in magento 2.

1. Using Dependency Injection

Add below code snippet in Block class.

protected $_customerFactory;
    
public function __construct(
	\Magento\Backend\Block\Template\Context $context,
	\Magento\Customer\Model\CustomerFactory $customerFactory,
	array $data = []
) 
{
	$this->_customerFactory = $customerFactory;
	parent::__construct($context, $data);
}

public function getCustomerCollection() 
{
	$collection = $this->_customerFactory->create()->getCollection()
			->addAttributeToSelect("*")
			->load();
	return $collection;
}

Add below code snippet in template file.

//Get customer collection
$customerCollection = $block->getCustomerCollection();

if ($customerCollection && count($customerCollection) > 0) {
    foreach ($customerCollection AS $customer) {
        echo $customer->getFirstname()."<br/>";
        echo $customer->getLastname()."<br/>";
        echo $customer->getEmail()."<br/>";
    }
}

 

2. Using Object Manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$customerFactory = $objectManager->create('Magento\Customer\Model\CustomerFactory')->create();

//Get customer collection
$customerCollection = $customerFactory->getCollection()
        ->addAttributeToSelect("*")
        ->load();

if ($customerCollection && count($customerCollection) > 0) {
    foreach ($customerCollection AS $customer) {
        echo $customer->getFirstname() . "<br/>";
        echo $customer->getLastname() . "<br/>";
        echo $customer->getEmail() . "<br/>";
    }
}

Thats it. Enjoy Magento 2!!