簡體   English   中英

Java 將 Spring Data Sort 轉換為 Comparator

[英]Java convert Spring Data Sort to Comparator

我構建了一個 Spring Boot 應用程序,它使用 Spring Data Sort 類對數據庫中的實體進行排序。 但是,出於一致性的原因,我還想將該排序機制應用於一般列表或流,因此需要將其轉換為Comparator

我想出了一個解決方案,但我覺得有一種更優雅和/或類型安全的方法來做到這一點。 有什么建議嗎?

import org.springframework.data.domain.Sort;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.util.Comparator;
import java.util.Iterator;

public class ComparatorUtils {
    public static <T> Comparator<T> convert(Sort sort, Class<T> type) {
        final Iterator<Sort.Order> orderIterator = sort.iterator();
        final Sort.Order order = orderIterator.next();

        Comparator<T> comparator = convert(order, type);
        while (orderIterator.hasNext()) {
            comparator = comparator.thenComparing(convert(orderIterator.next(), type));
        }

        return comparator;
    }

    private static <T> Comparator<T> convert(Sort.Order order, Class<T> type) {
        Comparator<T> comparator = Comparator.comparing((T entity) -> {
            try {
                return (Comparable) new PropertyDescriptor(order.getProperty(), type).getReadMethod().invoke(entity);
            } catch (IllegalAccessException | InvocationTargetException | IntrospectionException e) {
                throw new RuntimeException(e);
            }
        });

        if (order.isDescending())
            return comparator.reversed();
        return comparator;
    }
}
  • 使用 org.springframework.beans.BeanUtils.getPropertyDescriptor 緩存描述符(而不是新的 PropertyDescriptor)。
  • 此解決方案不處理按更深的字段排序(例如 Person.Address.Street)
  • 未正確處理空值。 使用 Comparator.nullsFirst 或 nullsLast。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM