【问题标题】:lexicographical ordering of string list using guava使用番石榴对字符串列表进行字典排序
【发布时间】:2011-02-03 11:21:39
【问题描述】:

使用番石榴进行字符串列表lexicographical ordering 的简单方法是什么。 我是这样做的:

List<String> s = newArrayList(
    "susen", "soumen", "dipak", "abhi", "zylo",
    "zala", "gautam", "gautom", "shaswasti", "saswati");
List<char[]> ts = newArrayList(transform(s, new Function<String, char[]>() {
    @Override
        public char[] apply(String input) {
            return input.toCharArray();
        }
    }));
Collections.sort(ts, Chars.lexicographicalComparator());
s = transform(ts, new Function<char[], String>() {
    @Override
    public String apply(char[] input) {
        return String.valueOf(input);
    }
});
System.out.println(s);

【问题讨论】:

  • 这太过分了。只需在 java.util 包中使用 Collections.sort

标签: java collections guava


【解决方案1】:

如果您不想就地排序,并且想使用番石榴,请查看Ordering

Ordering.natural().sortedCopy(yourInputThatIsIterableAndHasStrings);

或:

Ordering.usingToString().sortedCopy(yourInputThatIsIterableThatYouWantToSortBasedOnToString);

如果你想就地排序,那么你应该使用Collections.sort(...)

希望这会有所帮助。

【讨论】:

  • 还有immutableSortedCopy可以得到ImmutableList
【解决方案2】:

String 实现 Comparable,它的自然顺序是字典顺序。 你所要做的就是

Collections.sort(s);

【讨论】:

    【解决方案3】:

    简单地说(因为String实现了Comparable):

    List<String> s = ...
    Collections.sort(s);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多