Search code examples
javalambdacomparatorcomparable

Comparator: Comparing 2 objects with field which can be null


I need to write a Comparator by implementing a typical compare-method of a default comparator. This is given due to the interface I need to implement.

My objects are products with an Integer field vintage which can be null. Code is as following:

@Override
public int compare ( IProduct product1, IProduct product2 ) throws ProductComparisonException
{

    if ( product1 == null && product2 == null )
    {
        return 0;
    }
    else if ( product1 == null && product2 != null )
    {
        return -1;
    }
    else if ( product1 != null && product2 == null )
    {
        return 1;
    }

    IProductData productData1 = (IProductData ) product1.getProvidedProductData();
    IProductData productData2 = (IProductData ) product2.getProvidedProductData();

    if ( productData1.getVintage() == null && productData2.getVintage() == null )
    {
        return 0;
    }
    else if ( productData1.getVintage() == null && productData2.getVintage() != null )
    {
        return -1;
    }
    else if ( productData1.getVintage() != null && productData2.getVintage() == null )
    {
        return 1;
    }

    return productData2.getVintage().compareTo( productData2.getVintage() );
}

I am not satisfied with this, as I have a lot of duplicate code and I'm sure there's a better way to do this... Any suggestions would be appreciated.


Solution

  • How about this one?:

    Comparator<IProduct> comparator = (p1, p2) -> {
        Integer v1 = p1 != null ? p1.getProvidedProductData() : null;
        Integer v2 = p2 != null ? p2.getProvidedProductData() : null;
    
        if (v1 == null ^ v2 == null)
            return v1 != null ? 1 : -1;
    
        return v1 != null ? v1.compareTo(v2) : 0;
    };