Sort on a string that may contain a number

前端 未结 23 2311
走了就别回头了
走了就别回头了 2020-11-22 02:59

I need to write a Java Comparator class that compares Strings, however with one twist. If the two strings it is comparing are the same at the beginning and end of the strin

23条回答
  •  轮回少年
    2020-11-22 03:52

    Instead of reinventing the wheel, I'd suggest to use a locale-aware Unicode-compliant string comparator that has built-in number sorting from the ICU4J library.

    import com.ibm.icu.text.Collator;
    import com.ibm.icu.text.RuleBasedCollator;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Locale;
    
    public class CollatorExample {
        public static void main(String[] args) {
            // Make sure to choose correct locale: in Turkish uppercase of "i" is "İ", not "I"
            RuleBasedCollator collator = (RuleBasedCollator) Collator.getInstance(Locale.US);
            collator.setNumericCollation(true); // Place "10" after "2"
            collator.setStrength(Collator.PRIMARY); // Case-insensitive
            List strings = Arrays.asList("10", "20", "A20", "2", "t1ab", "01", "T010T01", "t1aB",
                "_2", "001", "_200", "1", "A 02", "t1Ab", "a2", "_1", "t1A", "_01",
                "100", "02", "T0010T01", "t1AB", "10", "A01", "010", "t1a"
            );
            strings.sort(collator);
            System.out.println(String.join(", ", strings));
            // Output: _1, _01, _2, _200, 01, 001, 1,
            // 2, 02, 10, 10, 010, 20, 100, A 02, A01, 
            // a2, A20, t1A, t1a, t1ab, t1aB, t1Ab, t1AB,
            // T010T01, T0010T01
        }
    }
    

提交回复
热议问题