如何使用JEXL对对象数组按type字段进行排序?
使用JEXL按type字段排序对象数组
要对给定的对象数组按type字段排序,你可以借助JEXL调用Java的Collections.sort方法,结合自定义比较器实现。以下是具体实现方案:
实现步骤与代码示例
假设你在Java环境中使用JEXL,代码如下:
import org.apache.commons.jexl3.JexlBuilder; import org.apache.commons.jexl3.JexlEngine; import org.apache.commons.jexl3.JexlExpression; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class JexlSortExample { public static void main(String[] args) { // 待排序的对象数组 List<Object> dataList = new ArrayList<>(); dataList.add(new Data(1, "John", 9)); dataList.add(new Data(2, "Doe", 7)); dataList.add(new Data(3, "Doe", 10)); // 初始化JEXL引擎 JexlEngine jexl = new JexlBuilder().create(); // 定义排序表达式:调用Collections.sort,自定义比较器按type字段升序排序 String sortExpr = "Collections.sort(data, new java.util.Comparator() { public int compare(a,b) { return a.type - b.type; } })"; JexlExpression expression = jexl.createExpression(sortExpr); // 准备上下文,传入待排序数组 org.apache.commons.jexl3.JexlContext context = new org.apache.commons.jexl3.MapContext(); context.set("data", dataList); context.set("Collections", Collections.class); // 执行排序 expression.evaluate(context); // 输出排序后的结果 dataList.forEach(item -> System.out.println(item)); } // 定义数据类(对应待排序的对象结构) static class Data { int id; String name; int type; public Data(int id, String name, int type) { this.id = id; this.name = name; this.type = type; } @Override public String toString() { return "Data{id=" + id + ", name='" + name + "', type=" + type + "}"; } } }
排序结果
执行上述代码后,数组会按type字段升序排列,结果如下:
Data{id=2, name='Doe', type=7} Data{id=1, name='John', type=9} Data{id=3, name='Doe', type=10}
如果需要降序排序,只需将比较器中的a.type - b.type改为b.type - a.type即可。
内容的提问来源于stack exchange,提问作者Ashish Bhumkar
相关产品推荐
相关产品推荐

