【问题标题】:i want to sort on custom sort based on some filter match values我想根据一些过滤器匹配值对自定义排序进行排序
【发布时间】:2023-02-16 19:23:54
【问题描述】:

我有 java 中的动态对象列表,如下所示,

{country='Japan', rate=81 },
{country='Brazil', rate=76 },
{country='China', rate=75 },
{country='Colombia', rate=69},
{country='South Korea', rate=54 },
{country='EU trade marks', rate=46 }

具有一些过滤条件,例如 50 到 70 评级或选定的国家/地区 [巴西,中国] 或者

我想要一个自定义排序机制,Java 8 或比较器等, 这样我就可以得到如下所示的排序数组,如果只有标准是从 50 到 70 评级,那么较高的比率是过滤标准中最重要的,其余的按降序排列。

*{country='Colombia', rate=69},
{country='South Korea', rate=54 },*
{country='Japan', rate=81 },
{country='Brazil', rate=76 },
{country='China', rate=75 },
{country='EU trade marks', rate=46 }

如果为所选国家/地区设置了条件 [巴西,中国] 那么无论比率如何,所选国家/地区首先按字母顺序排列,然后是从高到低的比率。

*{country='Brazil', rate=76 },
{country='China', rate=75 },*
{country='Japan', rate=81 },
{country='Colombia', rate=69},
{country='South Korea', rate=54 },
{country='EU trade marks', rate=46 }

【问题讨论】:

    标签: java arrays java-8 java-stream core


    【解决方案1】:

    您可以使用 Java 8 流和 Comparator 来实现基于过滤条件的自定义排序。这是一个示例代码 sn-p:

    List<Map<String, Object>> dataList = new ArrayList<>();
    // populate dataList with the dynamic objects
    
    // define the filter criteria
    List<String> selectedCountries = Arrays.asList("Brazil", "China");
    int minRating = 50;
    int maxRating = 70;
    
    // create a comparator based on the filter criteria
    Comparator<Map<String, Object>> comparator = Comparator.comparing((Map<String, Object> data) -> {
        String country = (String) data.get("country");
        int rate = (int) data.get("rate");
        // check if the country is in the selected list
        if (selectedCountries.contains(country)) {
            // return a high value to keep it on top
            return -1000 + selectedCountries.indexOf(country);
        } else if (rate >= minRating && rate <= maxRating) {
            // return the rate within the filter range
            return -rate;
        } else {
            // return the rate in descending order
            return -rate - 1000;
        }
    });
    
    // sort the dataList based on the comparator
    List<Map<String, Object>> sortedDataList = dataList.stream()
            .sorted(comparator)
            .collect(Collectors.toList());
    

    在此代码中,dataList 是一个动态对象列表。您需要用实际对象替换数据。筛选条件定义为 selectedCountries、minRating 和 maxRating。您可以根据需要修改这些值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-19
      • 2021-04-01
      • 1970-01-01
      • 2016-09-29
      • 2013-08-17
      • 1970-01-01
      相关资源
      最近更新 更多