Converting an int array to a String array

前端 未结 14 1428
予麋鹿
予麋鹿 2020-12-01 14:21

So I have this \"list\" of ints. It could be a Vector, int[], List, whatever.

My goal though is to sort the

14条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-01 14:44

    Simple solution using Guava:

    public List toSortedStrings(List ints) {
      Collections.sort(ints);
      return Lists.newArrayList(Iterables.transform(ints, 
          Functions.toStringFunction()));
    }
    

    Obviously, this solution (like any other) is going to use loops internally, but it gets it out of the code you have to read. You could also avoid changing the order in ints by passing the result of Ordering.natural().sortedCopy(ints) to transform instead of using Collections.sort first. Also, the Lists.newArrayList part is not necessary if you don't need to be able to add new elements to the resulting list.

    The shortened version of that method body, with static imports:

    return transform(Ordering.natural().sortedCopy(ints), toStringFunction());
    

提交回复
热议问题