Java: sort a String array, whose strings represent int

后端 未结 8 1164
北恋
北恋 2020-12-16 14:09

I have String[] array like

{\"3\",\"2\",\"4\",\"10\",\"11\",\"6\",\"5\",\"8\",\"9\",\"7\"}

I want to sort it in numerical ord

8条回答
  •  不思量自难忘°
    2020-12-16 14:41

    If all elements if your String array represent numbers, and if the numbers are always positive, then there is a simple way to sort numerically without a limit to the value of the number.

    This is based on the fact that a number with a larger number of digits is, in that case, always higher than a number with a smaller number of digits.

    You first compare the number of digits, and then (only if the number of digits is the same) you compare the value alphabetically:

    Arrays.sort(array,
                Comparator.comparing(String::length).thenComparing(Function.identity()));
    

提交回复
热议问题