List排序攻略

来源:互联网 发布:强制视频软件免费版 编辑:程序博客网 时间:2024/06/13 23:12

    今天用到了List排序的方法,原因是我们要对从数据库查询上来的题型List,按照实体的某个字段来排序,这样才能展现出如:选择题是第一题,填空题是第二题的试卷的样子。

具体代码如下:

 //根据paperid获取该试卷的题型信息        TemplatePaperQuestiontypeExample templatePaperQuestiontypeExample = new TemplatePaperQuestiontypeExample();        TemplatePaperQuestiontypeCriteria templatePaperQuestiontypeCriteria = templatePaperQuestiontypeExample.createCriteria();        templatePaperQuestiontypeCriteria.andTemplateorpaperIdEqualTo(paperid);        List<TemplatePaperQuestiontypeEntity> templatePaperQuestiontypeEntityList = templatePaperQuestiontypeDao.selectByExample(templatePaperQuestiontypeExample);

我们根据试卷id从数据库获取所有题型的信息。但是我们得到的List中的每个题型的顺序是不对的,这样直接在页面上显示是不对的,所以我们需要按照这个集合类型实体的题序字段来排序。


排序代码如下:

        //根据题型顺序对题型排序        Collections.sort(templatePaperQuestiontypeEntityList, new Comparator<TemplatePaperQuestiontypeEntity>() {            @Override            public int compare(TemplatePaperQuestiontypeEntity o1, TemplatePaperQuestiontypeEntity o2) {                //按照升序排序                if (o1.getQuestionTypeOrder()>o2.getQuestionTypeOrder()){                    return 1;                }                if (o1.getQuestionTypeOrder()<o2.getQuestionTypeOrder()){                    return -1;                }                return 0;            }        });
这是按照升序排列。
如果

 //按照降序排序                if (o1.getQuestionTypeOrder()<o2.getQuestionTypeOrder()){                    return 1;                }                if (o1.getQuestionTypeOrder()>o2.getQuestionTypeOrder()){                    return -1;                }                return 0;

则是按照降序排列。


原创粉丝点击