您的位置:首页 > 其它

随机位置+固定位置排序

2016-07-03 00:00 369 查看
摘要: 一组广告数据,需要其中几条随机排序,剩余几条按指定位置排序。

(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;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息