Is there a way to return a comparator that does nothing?

I have two classes propagating one parent class, and there is a method that sorts data by some parameter. Therefore, for one of these two classes, I need to apply some sorting, but do nothing for the other two. Is there such an opportunity?

public class MedicalCompositeRatesData{

  @Override
  public List<RateTableData> buildData(RateTableInputBean inputBean)
  {
    SGQuotingData sgQuotingData = inputBean.getQuotingData();

    List<ProductData> products = extractorFactory
      .getProductExtractor(inputBean.getPlanType(), inputBean.getRatingType())
      .extract(sgQuotingData);

    List<Row> rates = products.stream()
        .map(it -> buildRow(it, sgQuotingData))
        .sorted(getProductComparator())
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

    return buildRateTables(rates);
  }

  protected Comparator<Product> getProductComparator(){
    //should leave default sorting
  }

}

public class AlternateCompositeRatesBuilder extends MedicalCompositeRatesData
{

  protected Comparator<Product> getProductComparator(){
    //will sort by rate
  }

}
+4
source share
2 answers

Stream.sortmakes a stable view if the stream is streamlined. In other words, if two elements are equal, then they will retain their original order.

Thus, since your stream is created from List, you can simply make all elements equal:

protected Comparator<Product> getProductComparator() {
    return (a1, a2) -> 0;
}

It's not very cool looking, but it should do the job.

+8

guava , :

Ordering.allEqual();  

, ...

@Override
public int compare(@Nullable Object left, @Nullable Object right) {
  return 0;
}
0

Source: https://habr.com/ru/post/1678852/


All Articles