【java】实体类中 按照特定的字段 进行升序/降序 排序

简介: 背景:  实际页面上  所有的分值都是按照JSON格式存储在一个字符串中 存储在同一个字段中:{"ownPTotal":"10>0","ownOTotal":"8>0","ownTotal1":"18","ownTotal2":"80","ownTotal3":"20","ownTotal4"...

背景:

  实际页面上  所有的分值都是按照JSON格式存储在一个字符串中 存储在同一个字段中:

{"ownPTotal":"10>0","ownOTotal":"8>0","ownTotal1":"18","ownTotal2":"80","ownTotal3":"20","ownTotal4":"118","leadTotal1":"20","leadTotal2":"80","leadTotal3":"20","leadTotal4":"120","chiefCheck1":"","chiefCheck2":"","leadTotal5":"140"}

 

现在 需要按照 其中的 几种分值  进行升序/降序的排序操作

 

解决方法:

【因为不是按照原实体的中的字段进行排序,因此需要新建一个实体,将原实体中有用的字段和需要使用的值从字段中抽离出来 在新实体中设置成字段,如果需要进行排序的字段是原实体中就存在的,那就不需要新建实体了】

重点关注:

 

实现 Comparable接口需要实现的比较方法    这里动态比较 是按照 1.哪个字段进行排序   2.升序/降序

//排序方法
    @Override
    public int compareTo(NewMonthPerEntity o) {
        double a1 = this.whichProperty.equals("leadTotal5") ? this.leadTotal5 : (this.whichProperty.equals("leadTotal4") ? this.leadTotal4 :(this.whichProperty.equals("ownTotal4") ? this.ownTotal4 :this.ownTotal4));
        double a2 = o.whichProperty.equals("leadTotal5") ? o.leadTotal5 : (o.whichProperty.equals("leadTotal4") ? o.leadTotal4 :(o.whichProperty.equals("ownTotal4") ? o.ownTotal4 :o.ownTotal4));
        if(this.ascDesc){//若是升序
            return a1 > a2 ? 1  : -1;
        }else{
            return a1 > a2 ? -1 : 1;
        }
    }

 【注意:这里  return a1 > a2 ? 1 : -1;并没有写成  return a1 > a2 ? 1  :(a1==a2 ? 0 :-1);   这个样子,是因为如果在比较的时候判定两个相等 ,那在放入TreeSet中时会发生覆盖现象  】

 新实体完整代码:

  1 package com.agen.util;
  2 
  3 public class NewMonthPerEntity implements Comparable<NewMonthPerEntity>{
  4     
  5     private String monthPerId;            //月度考核Id
  6     private String userId;                //用户Id
  7     private String userName;            //用户名称
  8     private String createDate;        //考核创建时间
  9     private double leadTotal5;            //调控分值
 10     private double leadTotal4;            //考评分值
 11     private double ownTotal4;            //自评分值
 12     private boolean ascDesc;            //true升序/false降序
 13     private String whichProperty;        //需要对哪个分值排序
 14     
 15     
 16     
 17     
 18     
 19     public String getMonthPerId() {
 20         return monthPerId;
 21     }
 22 
 23     public void setMonthPerId(String monthPerId) {
 24         this.monthPerId = monthPerId;
 25     }
 26     public String getUserId() {
 27         return userId;
 28     }
 29     public void setUserId(String userId) {
 30         this.userId = userId;
 31     }
 32     public String getUserName() {
 33         return userName;
 34     }
 35     public void setUserName(String userName) {
 36         this.userName = userName;
 37     }
 38     public String getCreateDate() {
 39         return createDate;
 40     }
 41 
 42     public void setCreateDate(String createDate) {
 43         this.createDate = createDate;
 44     }
 45 
 46     public double getLeadTotal5() {
 47         return leadTotal5;
 48     }
 49     public void setLeadTotal5(double leadTotal5) {
 50         this.leadTotal5 = leadTotal5;
 51     }
 52     public double getLeadTotal4() {
 53         return leadTotal4;
 54     }
 55     public void setLeadTotal4(double leadTotal4) {
 56         this.leadTotal4 = leadTotal4;
 57     }
 58 
 59     public double getOwnTotal4() {
 60         return ownTotal4;
 61     }
 62 
 63     public void setOwnTotal4(double ownTotal4) {
 64         this.ownTotal4 = ownTotal4;
 65     }
 66     public boolean isAscDesc() {
 67         return ascDesc;
 68     }
 69 
 70     public void setAscDesc(boolean ascDesc) {
 71         this.ascDesc = ascDesc;
 72     }
 73 
 74     public String getWhichProperty() {
 75         return whichProperty;
 76     }
 77     public void setWhichProperty(String whichProperty) {
 78         this.whichProperty = whichProperty;
 79     }
 80 
 81     public NewMonthPerEntity(String monthPerId, String userId, String userName,
 82             String createDate, double leadTotal5, double leadTotal4,
 83             double ownTotal4) {
 84         super();
 85         this.monthPerId = monthPerId;
 86         this.userId = userId;
 87         this.userName = userName;
 88         this.createDate = createDate;
 89         this.leadTotal5 = leadTotal5;
 90         this.leadTotal4 = leadTotal4;
 91         this.ownTotal4 = ownTotal4;
 92     }
 93 
 94 
 95 
 96 
 97 
 98     public NewMonthPerEntity(String monthPerId, String userId, String userName,
 99             String createDate, double leadTotal5, double leadTotal4,
100             double ownTotal4, boolean ascDesc, String whichProperty) {
101         super();
102         this.monthPerId = monthPerId;
103         this.userId = userId;
104         this.userName = userName;
105         this.createDate = createDate;
106         this.leadTotal5 = leadTotal5;
107         this.leadTotal4 = leadTotal4;
108         this.ownTotal4 = ownTotal4;
109         this.ascDesc = ascDesc;
110         this.whichProperty = whichProperty;
111     }
112 
113 
114 
115 
116 
117 
118     //排序方法
119     @Override
120     public int compareTo(NewMonthPerEntity o) {
121         double a1 = this.whichProperty.equals("leadTotal5") ? this.leadTotal5 : (this.whichProperty.equals("leadTotal4") ? this.leadTotal4 :(this.whichProperty.equals("ownTotal4") ? this.ownTotal4 :this.ownTotal4));
122         double a2 = o.whichProperty.equals("leadTotal5") ? o.leadTotal5 : (o.whichProperty.equals("leadTotal4") ? o.leadTotal4 :(o.whichProperty.equals("ownTotal4") ? o.ownTotal4 :o.ownTotal4));
123         if(this.ascDesc){//若是升序
124             return a1 > a2 ? 1  : -1;
125         }else{
126             return a1 > a2 ? -1 : 1;
127         }
128     }
129     
130     
131     
132     
133     
134 }
View Code

 

@RequestMapping("allMonthPer")
    @ResponseBody
    public TreeSet<NewMonthPerEntity> allMonthPer(HttpServletRequest request,boolean ascDesc,String whichProperty) {
//-----------------部分代码---------------------------------------------------
.
.
.
.
//原实体 得到的List DetachedCriteria criteria = DetachedCriteria.forClass(Monthper.class); criteria.add(Restrictions.in("userId", userIds)); List<Monthper> monthPers = monthperService.list(criteria); //新建TreeSet 将原实体的List 对应的放置在新的实体中,放入TreeSet的时候就已经是按照传入【按照 哪个字段排序/升序或降序 】 排好顺序的 TreeSet<NewMonthPerEntity> newSet = new TreeSet<NewMonthPerEntity>(); for (Monthper monthper : monthPers) { String totalStr = monthper.getTotalStr(); double leadTotal5 = Double.parseDouble(JSONObject.fromObject(totalStr).getString("leadTotal5")); double leadTotal4 = Double.parseDouble(JSONObject.fromObject(totalStr).getString("leadTotal4")); double ownTotal4 = Double.parseDouble(JSONObject.fromObject(totalStr).getString("ownTotal4")); NewMonthPerEntity entity = new NewMonthPerEntity(monthper.getMonthPerId(),monthper.getUserId(),userService.get(monthper.getUserId()).getUserName(),monthper.getCreateDate().toLocaleString(),leadTotal5,leadTotal4,ownTotal4); entity.setAscDesc(ascDesc);//设置升序/降序 if("".equals(whichProperty) || null == whichProperty){ entity.setWhichProperty("ownTotal4"); }else{ entity.setWhichProperty(whichProperty); } newSet.add(entity); } return newSet;
//在前台 只需要$.each取出来 追加到页面就好 }

 

 

效果如下图:

 

 

 

 

附带 前台jsp代码

 1 <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
 2 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <title>考核列表</title>
12     
13     <meta http-equiv="pragma" content="no-cache">
14     <meta http-equiv="cache-control" content="no-cache">
15     <meta http-equiv="expires" content="0">    
16     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
17     
18     <link href="../bootstrap/css/bootstrap.min.css" rel="stylesheet">
19     <script src="../js/jquery.js"></script>   
20 
21   </head>
22   
23   <body>
24     
25     <div class="panel panel-primary">
26           <div class="panel-heading">
27                <div class="form-group"> 
28                  <label class="panel-title" >月度绩效考评列表</label>
29                  &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
30                    <button type="button" class="btn btn-success thisMonth">本月考核</button>
31                   <button type="button" class="btn btn-warning  userRefresh">刷新页面</button>
32                   <c:if test="${roleGrade==0 }">
33                       <div class="row">
34                           <div class="col-lg-2">
35                             <div class="input-group">
36                               <select class="form-control dep" name="departmentId">
37                                         <option value="0">可选择所在部门</option>
38                               </select>
39                             </div>
40                           </div>
41                           <div class="col-lg-1">
42                             <div class="input-group">
43                               <input type="text" class="form-control us"    placeholder="用户名称"  >
44                             </div>
45                           </div>
46                           <div class="col-lg-1">
47                             <div class="input-group">
48                               <input type="number" class=" form-control mon"   placeholder="查询月份"  >
49                             </div>
50                           </div>
51                           <div class="col-lg-1">
52                             <div class="input-group">
53                               <button type="button" class="btn btn-default mohu ">模糊查询</button>
54                             </div>
55                           </div>
56                         </div>
57                   </c:if>
58                   
59              </div> 
60           </div>
61           <div class="panel-body">
62           <input type="hidden" class="operationId" value="${operationId}"/>
63           <input type="hidden" class="whichProperty" />
64           <input type="hidden" class="ascDesc"/>
65           
66                 <table class="table text-center">
67                           <tr class="firstTr">
68                             <td class="active"> <input type="checkbox" id="checkAll" name="checkAll" /></td>
69                           <td class="primary"><h4>考核月份</h4></td>
70                           <td class="success"><h4>员工名称</h4></td>
71                           <td class="danger"><h4>考评时间</h4></td>
72                           <td class="warning"><h4>调控分值 <span class="glyphicon glyphicon-sort" alt="leadTotal5"  style="float: right;"></span></h4></td>
73                           <td class="info"><h4>考评分值 <span class="glyphicon glyphicon-sort"  alt="leadTotal4"  style="float: right;"></span></h4></td>
74                           <td class="danger"><h4>自评分值 <span class="glyphicon glyphicon-sort" alt="ownTotal4"  style="float: right;"></span></h4></td>
75                           <td class="default"><h4>操作</h4></td>
76                         </tr>
77                  </table>
78           </div>
79     </div>
80     
81   </body>
82   
83   <script src="../bootstrap/js/bootstrap.min.js"></script>
84   <script src="../layer/layer.js"></script>
85   <script type="text/javascript" src="../js/UUID.js"></script>
86   <script type="text/javascript" src="../js/perContent/monthPerContent/allMonth.js"></script>
87   
88 </html>
View Code

 

附带 前台js代码

 

  1 function refreshAll(ascDesc,whichProperty){
  2     $("table tbody tr").not(":first").remove();
  3     $.ajax({url:"../monthPerCon/allMonthPer.htmls",
  4         dataType:'json',
  5         type:"post",
  6         data:{ascDesc:ascDesc,whichProperty:whichProperty},
  7         traditional:false,
  8         success:function(data){
  9             var temp ="";
 10             $.each(data,function(i,d){
 11                 temp += '<tr>'
 12                             +' <td class="active"> '
 13                                 +'<input type="checkbox" id="checkAll" name="checkAll" />'
 14                                 +'<input type="hidden"  name="monthPerId" value="'+d.monthPerId+'"/>'
 15                             +'</td>'
 16                             +'<td class="primary">'
 17                                 +(new Date(d.createDate).getMonth()+"月考核")
 18                             +'</td>'
 19                             +'<td class="success">'
 20                                 +'<input type="hidden"  name="userId" value="'+d.userId+'"/>'
 21                                 +d.userName
 22                             +'</td>'
 23                             +'<td class="danger">'
 24                                 +d.createDate
 25                             +'</td>'
 26                             +'<td class="warning tips">'
 27                                 +'【调控分值:'+d.leadTotal5+'】'
 28                             +'</td>'
 29                             +'<td class="info tips">'
 30                                 +'【考评分值:'+d.leadTotal4+'】'
 31                             +'</td>'
 32                             +'<td class="danger tips">'
 33                                 +'【自评分值:'+d.ownTotal4+'】'
 34                             +'</td>'
 35                             +'<td class="default">'
 36                                 +'<a class="aClick"><i class="glyphicon glyphicon-list-alt"></i>详情</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="Adelete"><i class="glyphicon glyphicon-trash"></i>删除</a>'    
 37                             +'</td>'
 38                         +'</tr>';
 39                 $(".whichProperty").val(d.whichProperty);
 40                 $(".ascDesc").val(d.ascDesc);
 41             });
 42             $(".firstTr").after(temp);
 43             
 44             
 45             /*//判断 此时按那列排序 升序降序 改变图标
 46             var whichProperty = $(".whichProperty").val();
 47             var ascDesc = $(".ascDesc").val();
 48             var thisSpan;
 49             var cla = "";
 50             whichProperty == "ownTotal4"? thisSpan = $("span").eq(2):(whichProperty == "leadTotal4"? thisSpan = $("span").eq(1) :thisSpan = $("span").eq(0));
 51             ascDesc == "true" ? cla = "glyphicon glyphicon-sort-by-attributes" : cla="glyphicon glyphicon-sort-by-attributes-alt";
 52             $(thisSpan).attr("class",cla);*/
 53         }
 54     });    
 55 }
 56 
 57 
 58 
 59 
 60 
 61 function mohu(ascDesc,whichProperty,dep,us,mon){
 62     
 63     $("table tbody tr").not(":first").remove();
 64     $.ajax({url:"../monthPerCon/mohuAllMonthPer.htmls",
 65         dataType:'json',
 66         type:"post",
 67         data:{ascDesc:ascDesc,whichProperty:whichProperty,departmentId:dep,userName:us,month:mon},
 68         traditional:false,
 69         success:function(data){
 70             var temp ="";
 71             $.each(data,function(i,d){
 72                 temp += '<tr>'
 73                         +' <td class="active"> '
 74                             +'<input type="checkbox" id="checkAll" name="checkAll" />'
 75                             +'<input type="hidden"  name="monthPerId" value="'+d.monthPerId+'"/>'
 76                         +'</td>'
 77                         +'<td class="primary">'
 78                             +(new Date(d.createDate).getMonth()+"月考核")
 79                         +'</td>'
 80                         +'<td class="success">'
 81                             +'<input type="hidden"  name="userId" value="'+d.userId+'"/>'
 82                             +d.userName
 83                         +'</td>'
 84                         +'<td class="danger">'
 85                             +d.createDate
 86                         +'</td>'
 87                         +'<td class="warning tips">'
 88                             +'【调控分值:'+d.leadTotal5+'】'
 89                         +'</td>'
 90                         +'<td class="info tips">'
 91                             +'【考评分值:'+d.leadTotal4+'】'
 92                         +'</td>'
 93                         +'<td class="danger tips">'
 94                             +'【自评分值:'+d.ownTotal4+'】'
 95                         +'</td>'
 96                         +'<td class="default">'
 97                             +'<a class="aClick"><i class="glyphicon glyphicon-list-alt"></i>详情</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a class="Adelete"><i class="glyphicon glyphicon-trash"></i>删除</a>'    
 98                         +'</td>'
 99                     +'</tr>';
100             });
101             $(".firstTr").after(temp);
102             
103         }
104     });    
105 
106 }
107 
108 
109 
110 
111 
112 $(document).ready(function(){
113     refreshAll();
114     
115     //升序 降序
116     $("span").click(function(){
117         
118         var whichProperty = $(this).attr("alt");
119         if($(this).attr("class") == "glyphicon glyphicon-sort"){
120             $(this).attr("class","glyphicon glyphicon-sort-by-attributes-alt");
121         }else if($(this).attr("class") == "glyphicon glyphicon-sort-by-attributes-alt"){
122             $(this).attr("class","glyphicon glyphicon-sort-by-attributes");
123         }else if($(this).attr("class") == "glyphicon glyphicon-sort-by-attributes"){
124             $(this).attr("class","glyphicon glyphicon-sort-by-attributes-alt");
125         }
126         
127         $("span").not(this).attr("class","glyphicon glyphicon-sort");
128         var ascDesc = $(this).attr("class") == "glyphicon glyphicon-sort" ? false : ($(this).attr("class") == "glyphicon glyphicon-sort-by-attributes-alt" ? false : true);
129         
130         //判断是否模糊查询
131          var dep = $(".dep option:selected").val();
132          var us = $(".us").val();
133          var mon = $(".mon").val();
134          if(dep !="" || us !="" || mon !=""){//只要模糊查询有值
135              if(( parseInt(mon)<0 || parseInt(mon)>12 )){
136                  layer.msg("月份不正确",{icon:2,time:1000});
137                  $(".mon").val("");
138              }else{
139                  mohu(ascDesc,whichProperty,dep,us,mon);
140              }
141          }else{//否则  查询
142              refreshAll(ascDesc,whichProperty);
143          }
144         
145     });
146     
147     
148     
149     $(document).on("click",".aClick",function(){
150         var monthPerId = $(this).parents("tr").children().first().find("input:hidden").val();
151         location.href = "../monthPerCon/showThisMonper.htmls?monthPerId="+monthPerId;
152     });
153     $(document).on("click",".Adelete",function(){
154         var operationId = $(".operationId").val();//操作人的ID
155         var userId = $(this).parents("tr").children().eq(2).find(":hidden").val();//本条考核的人员
156         if(operationId != userId){
157             layer.msg("非本人无法删除!",{icon:2,time:2000});
158         }else{
159             var monthPerId = $(this).parents("tr").children().first().find("input:hidden").val();
160             var leadTotal4 = JSON.parse($(this).parents("tr").children().eq(4).find(":hidden").val()).leadTotal4;
161             if( !(leadTotal4 == undefined || leadTotal4=="") ){
162                 layer.msg("经理已经考评无法删除!");
163             }else{
164                 $.ajax({url:"../monthPerCon/deleteThisMonper.htmls",
165                     dataType:'json',
166                     type:"post",
167                     data:{monthPerId:monthPerId},
168                     traditional:false,
169                     success:function(data){
170                         if(data){
171                             layer.msg("删除成功",{icon:1,time:2000},function(){
172                                 refreshAll();
173                             });
174                         }else{
175                             layer.msg("删除失败",{icon:2,time:2000},function(){
176                                 refreshAll();
177                             });
178                         }
179                         
180                     }
181                 });
182             }
183         }
184         
185 //        location.href = "../monthPerCon/deleteThisMonper.htmls?monthPerId="+monthPerId;
186     });
187     
188     //跳转到本月考核页面
189     $(".thisMonth").click(function(){
190         location.href = "../monthPerCon/perContent.htmls";
191     });
192     
193     
194     //部门
195     $.getJSON("../department/showAlldepartment.htmls", function(data){
196           if(data!=null){
197               var temp = "";
198               $.each(data,function(i,a){
199                   temp+="<option value='"+a.departmentId+"'>"+a.departmentName+"</option>";
200               });
201               $('.dep option').first().after(temp);
202           }
203     });
204     
205     
206     //模糊查询
207      $(".mohu").click(function(){
208          var dep = $(".dep option:selected").val();
209          var us = $(".us").val();
210          var mon = $(".mon").val();
211          if(( parseInt(mon)<0 || parseInt(mon)>12 )){
212              layer.msg("月份不正确",{icon:2,time:1000});
213              $(".mon").val("");
214          }else{
215              mohu(false,"ownTotal4",dep,us,mon);
216          }
217          
218      });
219     
220     
221 });
View Code

 

相关文章
|
28天前
使用ueditor实现多图片上传案例——实体类(Shopping.java)
使用ueditor实现多图片上传案例——实体类(Shopping.java)
18 0
|
28天前
|
Java
java实现遍历树形菜单方法——实体类VoteTree
java实现遍历树形菜单方法——实体类VoteTree
11 0
|
24天前
|
Java 数据库连接
hibernate注解实体类(Dept.java)
hibernate注解实体类(Dept.java)
13 1
|
26天前
|
Java
java面向对象高级分层实例_实体类
java面向对象高级分层实例_实体类
10 1
|
24天前
|
Java 数据库连接
hibernate注解实体类(Emp.java)
hibernate注解实体类(Emp.java)
13 1
|
28天前
|
Java 计算机视觉
java实现人脸识别源码【含测试效果图】——实体类(Users)
java实现人脸识别源码【含测试效果图】——实体类(Users)
10 0
|
1月前
|
Java
如何使用 Java 8 进行字符串排序?
【2月更文挑战第21天】
66 3
|
2月前
|
Java
Java排序
【2月更文挑战第7天】【2月更文挑战第17篇】List对象集合自定义排序,列出了以前的用法以及新用法。
25 0
|
2月前
|
存储 Java
Java TreeMap:基于红黑树的排序映射解析
Java TreeMap:基于红黑树的排序映射解析
|
2月前
|
安全 Java
Java TreeSet:基于红黑树的排序集合解析
Java TreeSet:基于红黑树的排序集合解析