源数据如下,要求对该list针对osVersion字段进行排序
[ { "osVersion": "11.3.1", "num": 100 }, { "osVersion": "5.1.2", "num": 43 }, { "osVersion": "10.3", "num": 23 }, { "osVersion": "7.0.3", "num": 55 }, { "osVersion": "15.1.1", "num": 47 } ]
下面贴可执行代码
package xxx.xxx.xxx.test; import com.alibaba.fastjson.JSON; import org.springframework.util.ObjectUtils; import java.util.Comparator; import java.util.List; public class VersionSort { public static class VersionData { private String osVersion; private Long num; public String getOsVersion() { return osVersion; } public void setOsVersion(String osVersion) { this.osVersion = osVersion; } public Long getNum() { return num; } public void setNum(Long num) { this.num = num; } } public static void main(String[] args) { // 这里jsonStr放上面贴出来的源数据 String jsonStr = ""; ListversionDataList = JSON.parseArray(jsonStr, VersionData.class); versionDataList.sort(Comparator.comparing(item -> getOsVersionValue(item.osVersion))); System.out.println(JSON.toJSonString(versionDataList)); } private static Integer getOsVersionValue(String osVersion) { if (ObjectUtils.isEmpty(osVersion)) { return 0; } String[] arr = osVersion.split("\."); Integer value = 0; for (int i = 0, j = 2; i < arr.length; i++, j--) { Double val = Math.pow(10, j); value += Integer.parseInt(arr[i]) * val.intValue(); } return value; } }
执行main方法,成功得到排序结果,如果需要逆序,则对结果集进行一次reverse即可
[{ "num": 43, "osVersion": "5.1.2" }, { "num": 55, "osVersion": "7.0.3" }, { "num": 23, "osVersion": "10.3" }, { "num": 100, "osVersion": "11.3.1" }, { "num": 47, "osVersion": "15.1.1" }]
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)