import com.xcar.hbase.common.pojo.RowData;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class CompareFunction implements Comparator<RowData> {
private List<String> list;
public CompareFunction(List<String> list) {
this.list = list;
}
@Override
public int compare(RowData o1, RowData o2) {
List<Integer> ss = new ArrayList<>();
for (String k : list) {
String[] split = k.split(":");
String field = split[0];
String sort = split[1];
String type = split[2];
int res;
String s1 = o1.getKeyValues().getOrDefault(field, null);
String s2 = o2.getKeyValues().getOrDefault(field, null);
if (StringUtils.isBlank(s1) && !StringUtils.isBlank(s2)) {
return 1;
} else if (!StringUtils.isBlank(s1) && StringUtils.isBlank(s2)) {
return -1;
} else if (StringUtils.isBlank(s1) && StringUtils.isBlank(s2)) {
return 0;
} else {
if ("int".equals(type)) {
res = Integer.valueOf(s1) - Integer.valueOf(s2);
} else if("long".equals(type)){
long l = Long.valueOf(s1) - Long.valueOf(s2);
if(l<0){
res=-1;
}else if(l>0){
res=1;
}else {
res=0;
}
}else if("double".equals(type)){
double v = Double.valueOf(s1) - Double.valueOf(s2);
if(v<0){
res=-1;
}else if(v>0){
res=1;
}else {
res=0;
}
} else {
res = o1.getKeyValues().get(field).compareTo(o2.getKeyValues().get(field));
}
}
if ("desc".equals(sort)) {
res = -res;
}
ss.add(res);
}
for (Integer f : ss) {
if (f > 0) {
return 1;
} else if (f < 0) {
return -1;
}
}
return 0;
}
}
调用:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class RowData {
String rowkey;
Map<String,String> keyValues;
}
public List<RowData> formatData(List<RowData> rowDataList,BigShip bigShip){
JSONArray sort = bigShip.getSort();
if(!sort.isEmpty()){
List<String> list = sort.toJavaList(String.class);
rowDataList.sort(new CompareFunction(list));
}
return rowDataList;
}
网友评论