Java排序(灵活定义排序策略)
编程技术  /  houtizong 发布于 3年前   96
/** * 普通学生的比较类 * 先根据id排序,后根据name排序 */import java.util.Comparator;import com.crystalcoding.beans.CommonStudent;@SuppressWarnings("rawtypes")public class CommonComp implements Comparator{ public int compare(Object obj0, Object obj1) { CommonStudent s0 = (CommonStudent) obj0; CommonStudent s1 = (CommonStudent) obj1; //先比较ID的大小 int compId = s0.getId().compareTo(s1.getId()); //三段式返回 return 0 != compId ? compId : s0.getName().compareTo(s1.getName()); }}
//信息丰富的学生类public class EnrichStudent{ private String id; private String name; private HashMap<String, String> attributes;}
package com.crystalcoding.sort.test;import java.util.Comparator;import java.util.List;import com.crystalcoding.beans.EnrichStudent;@SuppressWarnings("rawtypes")public class ComplicateComp implements Comparator{ //用于保存比较的属性列表 private List<String> keys; //比较类的构造函数 public ComplicateComp(List<String> keys) { this.keys = keys; } public int compare(Object obj0, Object obj1) { EnrichStudent s0 = (EnrichStudent) obj0; EnrichStudent s1 = (EnrichStudent) obj1; //属性列表遍历 for (int i = 0; i < keys.size(); i++) { String key = keys.get(i); String value0 = s0.getAttributes().get(key); String value1 = s1.getAttributes().get(key); int compResult = value0.compareTo(value1); if (0 != compResult) { return compResult; } else { if (i == keys.size() - 1) { return 0; } } } return 0; }}
public static void main(String[] args) throws IOException { //普通情况的排序 List<CommonStudent> commonList = initCommonList(); Collections.sort(commonList, new CommonComp()); print(commonList); //信息丰富的学生排序 List<EnrichStudent> enrichList = initComplicateList(); Collections.sort(enrichList, new EnrichComp()); print(enrichList); //更加通俗的排序 List<EnrichStudent> complicateList = initComplicateList(); List<String> keys = new ArrayList<String>(); keys.add("id"); keys.add("name"); keys.add("count"); Collections.sort(complicateList, new ComplicateComp(keys)); print(complicateList); }
请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!
技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成
网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];
文章归档
文章标签
友情链接