随机位置+固定位置排序
2016-07-03 00:00
369 查看
摘要: 一组广告数据,需要其中几条随机排序,剩余几条按指定位置排序。
(1)广告对象
Advertisement{
(2)对一组广告数据排序
List<Advertisement> advertisements ;
list详情:
Advertisement ad1 ; //location =2;固定位置
Advertisement ad2 ;//location =3; 固定位置
Advertisement ad3,ad4,ad5; //location =0 随机位置
(3)排序算法
(1)广告对象
Advertisement{
private Integer id; private String name; private String text; private String img; private String link; private Date startTime; private Date endTime; private Integer location; //广告位置 location=0时随机 private Date createTime; private Date updateTime; private Integer isDel; private Integer priority; }
(2)对一组广告数据排序
List<Advertisement> advertisements ;
list详情:
Advertisement ad1 ; //location =2;固定位置
Advertisement ad2 ;//location =3; 固定位置
Advertisement ad3,ad4,ad5; //location =0 随机位置
(3)排序算法
List<Advertisement> list = new ArrayList<>(); if(!CollectionUtils.isEmpty(advertisements)){ List<Integer> fixedIndex = new ArrayList<>(); // 固定的位置索引 List<Advertisement> fixedLocation = new ArrayList<>(); //固定位置的广告 List<Advertisement> randomLocation = new ArrayList<>(); //位置随机的广告 Queue<Advertisement> fixedQueue = new LinkedList<>(); //固定位置广告队列 Queue<Advertisement> randomQueue = new LinkedList<>();//随机位置广告队列 //先筛选其中随机部分,固定部分 for(Advertisement p: advertisements){ if(null != p.getLocation() && p.getLocation()>0){ fixedLocation.add(p); fixedIndex.add(p.getLocation()-1); //数组下标从0开始,位置2,数组index是1 }else{ randomLocation.add(p); //随机的 } } //随机排序 if(randomLocation.size()>0){ Collections.shuffle(randomLocation); //随机打乱 for(Advertisement p : randomLocation){ randomQueue.add(p); //随机位置广告队列 } } //固定排序,固定位置的广告按照位置大小排序 if(!CollectionUtils.isEmpty(fixedLocation)){ Collections.sort(fixedLocation, new Comparator<Advertisement>() { @Override public int compare(Advertisement o1, Advertisement o2) { return (o1.getLocation() == o2.getLocation() ? 0 : (o1.getLocation() > o2.getLocation() ? 1 : -1)); } }); for(Advertisement p : fixedLocation){ fixedQueue.add(p); } } //遍历数组,如果该位置是固定的,从固定位置广告队列取一条广告,如果该位置是随机的,从随机广告队列取一条广告 for(int i=0;i<advertisements.size();i++){ //该位置是固定数 if(fixedIndex.contains(i)){ if(!fixedQueue.isEmpty()) { list.add(fixedQueue.poll()); } }else{ if(!randomQueue.isEmpty()) { list.add(randomQueue.poll()); } } } } return list;
相关文章推荐
- elasticsearch分页列表查询
- Yii2实用基础学习笔记(零):Windows下通过Composer安装Yii2
- Yii2实用基础学习笔记(一):模型、视图与控制器
- Yii2实用基础学习笔记(二):Html助手和Request组件
- Yii2实用基础学习笔记(三):Url助手与分页组件
- Yii2实用基础学习笔记(四):模型验证
- Yii2实用基础学习笔记(五):CURD
- 盒子模型
- eclipse导入myeclipse的web项目没法识别问题解决
- lae界面开发工具入门之介绍九--<lua脚本组件篇>
- C++中的类型转换static_cast、dynamic_cast、const_cast和reinterpret_cast总结
- JDBC--调用函数与存储过程
- Spring源码解读2——Bean资源的载入/解析
- Spring源码解读3——Bean资源的注册
- pycharm 快捷键
- Maven Drools6.4.0.Final和Spring 整合
- 7. Jsp 自定义标签
- 再探C++Primer (3)关于unicode和多字节字符集
- Windows 安装配置 Apache .zip
- Spinner