Java排序类似IP这样的不定长的字符串进行排序-IP排序
根据类似IP这样的字符串进行排序
有时难免遇到类似IP或者其他字符分割的单号等等,这样的字段进行排序。排序思想大致就是根据字符切割开,然后再从前往后比较。
因为我用的是数字大小进行比较的,不能使用string的默认排序,不然1001竟然会排在2的前面。要是直接用切割后的那段字符串作为排序字段的杠精请绕道。
根据字符串切割方式很多,split、正则····
网上看到枚举方式的很耳目一新,就是使用 StringTokenizer
据说这个方法效率高,而且同时满足我这儿只是简单的单个切割来比较排序需求,同时能大量简化我的代码,何乐而不为呢。
贴一下链接 java中subString、split、stringTokenizer三种截取字符串方法的性能比较
(https://blog.csdn.net/adsadadaddadasda/article/details/82941528)
用java的lambda表达式简单演示一下
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;
/**
* @author HelloHiMonkey
* 根据类似IP这样的字符串进行排序
* 有时难免遇到类似IP或者其他字符分割的单号等等,这样的字段进行排序。排序思想大致就是根据字符切割开,然后再从前往后比较。
* 因为我用的是数字大小进行比较的,不能使用string的默认排序,不然1001竟然会排在2的前面。要是直接用切割后的那段字符串作为排序字段的杠精请绕道。
* 根据字符串切割方式很多,split、正则····
* 网上看到枚举方式的很耳目一新,就是使用StringTokenizer
* 用java的lambda表达式简单演示一下
*/
public class SortLikeIpString {
public static void main(String args[]){
List<String> list = Arrays.asList(
"003.322.805.822.840.438.220.274",
"055.786.157.416.245",
"077.134.673.105.355.003.758.727.066",
"085.013.435.523.224",
"152.441.564.586.073",
"152.177.480",
"152.465.444.522.626.526.568",
"152.177.480.748.018.647.570",
"323.624",
"356.773.718.782.171.536.871",
"364.180.121.483.601.678.067",
"402.107.014",
"472.602.046",
"472.602.046.263.170",
"472.602.046.263.803",
"527.530.350.778.137.513.335",
"536.017.404.734.537.134.241",
"604.255.236.550",
"640.117.263.314.358.353.678",
"677.873.326.803.167.528.474",
"733.212.422",
"783.850.435.605.204.862.722.563.417",
"800.461.476.404.442.666.212",
"810.454.842.314.848.623",
"823.405.158.606",
"833.204.283.833.320.664.236",
"854.367.556.645.628.764.760"
);
list.stream().sorted((e1,e2) -> {
StringTokenizer token=new StringTokenizer(e1,".");
StringTokenizer token2=new StringTokenizer(e2,".");
while (token.hasMoreTokens() && token2.hasMoreTokens()){
int parseInt = Integer.parseInt(token.nextToken());
int parseInt2 = Integer.parseInt(token2.nextToken());
if(parseInt > parseInt2) {
return 1;
}
if(parseInt < parseInt2) {
return -1;
}
}
if(token.hasMoreElements()) { // e1还有值,则e2已遍历完
return 1;
}else {
return -1;
}
}).forEach(System.out::println);
}
}
控制台最终结果展示
003.322.805.822.840.438.220.274
055.786.157.416.245
077.134.673.105.355.003.758.727.066
085.013.435.523.224
152.177.480
152.177.480.748.018.647.570
152.441.564.586.073
152.465.444.522.626.526.568
323.624
356.773.718.782.171.536.871
364.180.121.483.601.678.067
402.107.014
472.602.046
472.602.046.263.170
472.602.046.263.803
527.530.350.778.137.513.335
536.017.404.734.537.134.241
604.255.236.550
640.117.263.314.358.353.678
677.873.326.803.167.528.474
733.212.422
783.850.435.605.204.862.722.563.417
800.461.476.404.442.666.212
810.454.842.314.848.623
823.405.158.606
833.204.283.833.320.664.236
854.367.556.645.628.764.760