正規表現は、文字列から最後の桁を取得し、それらをソートします

Saurabhクマー:

私は文字列の最後の桁存在を使用してそれらをソートしたい文字列のリストを持って、私は、コードの下に使用し、これを試してみましたが、いくつかの理由のために、それは「ABC内のインスタンスのために、同様に最後の数字の前に桁の存在を選びましたそのうち、それは間違ってそれをソートされているので、それだけではなく、5の25を選んだ\ xyzの2 5" の文字列。私は正規表現で間違って何を知ってもいいですか?

注:私の最後の2桁は常に1571807700009 1571807700009のようなタイムスタンプになります。

ここで私はこれまでにしようとしているものです。

public static void second() {   
List<String> strings = Arrays.asList("abc\\xyz 2 5", "abc\\\\xyz 1 8", "abc\\\\xyz 1 9", "abc\\\\xyz 1 7", "abc\\\\xyz 1 3");       
Collections.sort(strings, new Comparator<String>() {
        public int compare(String o1, String o2) {
            return (int) (extractInt(o1) - extractInt(o2));
        }

        Long extractInt(String s) {
            String num = s.replaceAll("\\D", "");
            return Long.parseLong(num);
        }
    });
    System.out.println(strings);

}

出力

[abc\\xyz 1 3, abc\\xyz 1 7, abc\\xyz 1 8, abc\\xyz 1 9, abc\xyz 2 5]

予想される出力

[abc\\xyz 1 3, abc\\xyz 2 5, abc\\xyz 1 7, abc\\xyz 1 8, abc\xyz 1 9]
WJS:

ソートだけ空の文字列と文字列の前の部分を置き換えることによって、最後の整数で、ストリームを使用して。また、APIの利用の取ることができますComparator比較する方法にその値を渡すことによってインタフェースを。

   List<String> strings = Arrays.asList("abc\\xyz 2 5", "abc\\\\xyz 1 8",
      "abc\\\\xyz 1 9", "abc\\\\xyz 1 7", "abc\\\\xyz 1 3");

   strings = strings.stream()
       .sorted(Comparator.comparing(s -> Long.valueOf(s.replaceAll(".*\\s+", ""))))
       .collect(Collectors.toList());

   System.out.println(strings);

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=331083&siteId=1