How to get product collection by product sku in magento 2?

You can get product data by product SKU in Magento 2 by below code snippets,

<?php

namespace Rbj\Training\Block;

class Product extends \Magento\Framework\View\Element\Template
{
    /**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    /**
    * Get Product by SKU
    * @param mixed
    * @return \Magento\Catalog\Model\Product $product
    */
    public function getProductBySKU($sku)
    {
        try {
            $product = $this->productRepository->get($sku);
        } catch (\Exception $exception) {
            throw new \Magento\Framework\Exception\NoSuchEntityException(__('Such product doesn\'t exist'));
        }
        return $product;
    }
}

Call product collection under the template file by below code,

$sku = '24-MB01';
$product = $block->getProductBySKU($sku);
echo $product->getName(); // product name
echo $product->getId(); // product id

How to get product collection by product id in magento 2?

You can get product data by product id in Magento 2 by below code snippets,

<?php

namespace Rbj\Training\Block;

class Product extends \Magento\Framework\View\Element\Template
{
    /**
     * Constructor
     *
     * @param \Magento\Framework\View\Element\Template\Context  $context
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        array $data = []
    ) {
        $this->productRepository = $productRepository;
        parent::__construct($context, $data);
    }

    /**
    * Get Product by Id
    * @param int
    * @return \Magento\Catalog\Model\Product $product
    */
    public function getProduct($id)
    {
        return $this->productRepository->getById($id);
    }
}

Call inside template file by below code,

$product_id = 1;
$product = $block->getProduct($product_id);
echo $product->getName(); // product name
echo $product->getSku(); // product sku