因開發需要對一組sku的圖片進行排序,排序字段爲圖片名,排序方式爲升序,
圖片名命名規則: sku-圖片數字序號.jpg 或 特殊字符-圖片數字序號.jpg 或 中文.圖片數字序號.jpg 等等 命名規則很亂,因爲獲取的是第三方的數據,但是不變的是圖片數字序號前面的前綴,不同的sku中間的分隔符可能也會變,因此,我採用了將整個圖片名進行排序,這樣一組sku的圖片只存在圖片數字一個變量,其他爲定量.
首先說爲什麼要根據字節加長度進行排序,因爲如果僅僅根據字節進行排序,當圖片數字序號不再是個位數時,字符串比較並不會考慮到個位,十位情況等等這些情況,例如 字符串3比字符串10的字節大,因此,我們需要添加上長度進行判斷.
首先演示下不考慮長度的情況 排序結果
代碼如下:
@Test
public void testGetStringByteLength(){
Map<String,String> images = new HashMap<>();
images.put("101003706-1.JPG","1");
images.put("101003706-2.JPG","2");
images.put("101003706-3.JPG","3");
images.put("101003706-4.JPG","4");
images.put("101003706-10.JPG","10");
images.put("101003706-11.JPG","11");
images.put("101003706-副本.png","6");
images.put("101003706-5.JPG","5");
Set<String> strings = images.keySet();
List<String> s = new ArrayList<>();
for (String key : strings){
s.add(key);
}
System.out.println(s);
s.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o1.compareTo(o2);
}
});
System.out.println(s);
}
排序前:
排序後:
以下爲考慮長度的情況 排序結果
代碼如下:
@Test
public void testGetStringByteLength(){
Map<String,String> images = new HashMap<>();
images.put("101003706-1.JPG","1");
images.put("101003706-2.JPG","2");
images.put("101003706-3.JPG","3");
images.put("101003706-4.JPG","4");
images.put("101003706-10.JPG","10");
images.put("101003706-11.JPG","11");
images.put("101003706-副本.png","6");
images.put("101003706-5.JPG","5");
Set<String> strings = images.keySet();
List<String> s = new ArrayList<>();
for (String key : strings){
s.add(key);
}
System.out.println(s);
s.sort(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
if (o1.length() == o2.length()){
return o1.compareTo(o2);
}else{
if (o1.length() > o2.length()){
return 1;
}else{
return -1;
}
}
}
});
System.out.println(s);
}
排序前:
排序後: