1. 程式人生 > >Java排行榜中多級排序的一種正確實現方式

Java排行榜中多級排序的一種正確實現方式

需求:1,外層根據參與人數排序,並據此分頁

            2,內層首先根據級別排序,級別相同時,按照票數排序,固定展示8條

實現基礎:ArrayList

可能的坑:僅僅對最外層list執行一次排序呼叫,此時,無法確保總是正確,有時正確

正確姿勢:首先對每個內層list執行排序,然後加入外層list,最後對外層list執行一次排序

程式碼實戰:

1.內層model


import lombok.Data;

/**
 * @Author: feeler
 * @Date: 2018/07/12 21:17
 * @Description:
 */
@Data
public class PlayerKillingVideoUserInfo implements Comparable<PlayerKillingVideoUserInfo> {

    private String userid;

    private int source;

    private String userName;
    
    private String headImageUrl;

    private String pkDate;

    private String videoId;

    private long voteCount;

    private int currentLevel;


    /** high to low with currentLevel or voteCount*/
    @Override
    public int compareTo(PlayerKillingVideoUserInfo o) {
        if(this.currentLevel > o.currentLevel) {
            return -1;
        } else if(this.currentLevel < o.currentLevel) {
            return 1;
        } else {
            if(this.voteCount > o.voteCount) {
                return -1;
            } else if(this.voteCount < o.voteCount) {
                return 1;
            } else {
                return 0;
            }
        }
    }
}

2.外層model


import com.services.mapper.database.model.PlayerKillingVideoUserInfo;
import lombok.Data;

import java.util.List;

/**
 * @Author: feeler
 * @Date: 2018/07/13 15:37
 * @Description:
 */
@Data
public class ThemeRankInfo implements Comparable<ThemeRankInfo>{

    private long invovledCount;
    private long pageCount;
    private List<PlayerKillingVideoUserInfo> playerKillingVideoUserInfoList;

    @Override /** 由高到低 */
    public int compareTo(ThemeRankInfo o) {
        if(this.invovledCount > o.invovledCount) {
            return -1;
        } else if(this.invovledCount < o.invovledCount) {
            return 1;
        } else {
            return 0;
        }
    }
}

3. 排序方式

 for(PlayerKillingThemeDto playerKillingThemeDto: playerKillingThemeDtoList) {
                ThemeRankInfo themeRankInfo = new ThemeRankInfo();
                themeRankInfo.setPageCount(pageCount);
                for (PlayerKillingVideoUserDto playerKillingVideoUserDto : playerKillingVideoUserDtoList) {
                    PlayerKillingVideoUserInfo playerKillingVideoUserInfo = new PlayerKillingVideoUserInfo();
                    ......
                    playerKillingVideoUserInfo.setCurrentLevel(playerKillingVideoUserDto.getCurrentLevel());
                    playerKillingVideoUserInfoList.add(playerKillingVideoUserInfo);
                }
                /**step 1 sort*/
                Collections.sort(playerKillingVideoUserInfoList);
                themeRankInfo.setPlayerKillingVideoUserInfoList(playerKillingVideoUserInfoList);
                themeRankInfoList.add(themeRankInfo);
            }

  /**step 2 sort*/
  Collections.sort(themeRankInfoList);