How to Get Related Products Collection in Magento 2?

Related product collection in Magento 2 on the product detail page.

Related Products share the same group or category as the current product of the page.

You can see a list of related products by text “Related Products” in the product page. Its list of products related to the product with some cases, color or size variation is changed for the product.

<?php
namespace Jesadiya\Related\Model;

use Psr\Log\LoggerInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;

class RelatedProductList
{
    /**
     * @var ProductRepositoryInterface
     */
    protected $productRepositoryInterface;

    /**
     * @var LoggerInterface
     */
    private $logger;

    public function __construct(
        ProductRepositoryInterface $productRepositoryInterface,
        LoggerInterface $logger
    ) {
        $this->logger = $logger;
        $this->productRepositoryInterface = $productRepositoryInterface;
    }

    /**
     * get related products
     *
     * @return array
     */
    public function getRelatedProductsList()
    {
        $productId = 1;
        $relatedProduct = [];
        try {
            $product = $this->productRepositoryInterface->getById($productId);
            $related = $product->getRelatedProducts();

            if (count($related)) {
                foreach ($related as $item) {
                    $relatedProduct[] = $item->getId();
                }
            }
        } catch (\Exception $exception) {
            $this->logger->error($exception->getMessage());
        }

        return $relatedProduct;
    }
}

If the Product has the available related products, You can get the list of ids of the product.

Output:
Related product ids array.
If the related product is not assigned result will be an empty array.