2018년 11월 7일 수요일

[Java] Collections Sort Example (String with Numbers)


1. Collections Sort Example
1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;

import net.lingala.zip4j.model.FileHeader;

public class SortUtil {
    
    public static int compareStringNumber(String s1, String s2) {
        String[] s1Parts = s1.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
        String[] s2Parts = s2.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
        int i = 0;
        while(i < s1Parts.length && i < s2Parts.length){
            if(s1Parts[i].compareTo(s2Parts[i]) == 0){ //if parts are the same
                ++i;
            }else{
                try{
                    int intS1 = Integer.parseInt(s1Parts[i]);
                    int intS2 = Integer.parseInt(s2Parts[i]);
                    int diff = intS1 - intS2; 
                    if(diff == 0){
                        ++i;
                    }else{
                        return diff;
                    }
                }catch(Exception ex){
                    return s1.compareTo(s2);
                }
            }
        }
        if(s1.length() < s2.length()){
            return -1;
        }else if(s1.length() > s2.length()){
            return 1;
        }else{
            return 0;
        }
    }  

    public static void sortStringNumber(List<String> strings) {
        Collections.sort(strings, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return compareStringNumber(s1, s2);
            }
        });
    }
    
    public static void sortFiles(List<File> strings) {
        Collections.sort(strings, new Comparator<File>() {
            public int compare(File s1, File s2) {
                return compareStringNumber(s1.getPath(), s2.getPath());
            }
        });
    }
    
    public static void sortZipFileHeader(List<FileHeader> strings) {
        Collections.sort(strings, new Comparator<FileHeader>() {
            public int compare(FileHeader f1, FileHeader f2) {
                return compareStringNumber(f1.getFileName(), f2.getFileName());
            }
        });
    }
    
    public static void sortZipEntry(List<ZipArchiveEntry> strings) {
        Collections.sort(strings, new Comparator<ZipArchiveEntry>() {
            public int compare(ZipArchiveEntry f1, ZipArchiveEntry f2) {
                return compareStringNumber(f1.getName(), f2.getName());
            }
        });
    }

}

댓글 없음:

댓글 쓰기