按字母顺序对数组进行排序

2024-03-26

我有一个数组,我需要按出现次数对其元素进行排序,然后按字母顺序排序。 例如:

55 The
32 ASomething
32 BSomething

ASomething should come before Bsomething because:
1) they have the same number
2) A comes before B alphabetically

所以你首先按出现次数排序,然后按字母顺序排序

最好的方法是什么? 我正在使用合并排序对计数进行排序,但如何放置一个声明,它将检查它们是否具有相同的数字,它按字母顺序排序(可能超过 2 个单词)。

解决方案:在对数据计数进行合并排序之前,我所做的是对数据进行合并排序,这已经足够好了:)感谢大家的帮助


你需要定制Comparator http://java.sun.com/javase/6/docs/api/java/util/Comparator.html为此使用Arrays.sort() http://download.oracle.com/javase/6/docs/api/java/util/Arrays.html#sort(T%5B%5D,%20java.util.Comparator):

Arrays.sort(array, new CustomComparator());

public class CustomComparator implements Comparator<String> {
  private final Pattern pattern = Pattern.compile("(\\d+)\\s+(.*)");

  public int compare(String s1, String s2) {
    Matcher m1 = pattern.matcher(s1);
    if (!m1.matches()) {
      throw new IllegalArgumentException("s1 doesn't match: " + s1);
    }
    Matcher m2 = pattern.matcher(s2);
    if (!m2.matches()) {
      throw new IllegalArgumentException("s2 doesn't match: " + s2);
    }
    int i1 = Integer.parseInt(m1.group(1));
    int i2 = Integer.parseInt(m2.group(1));
    if (i1 < i2) {
      return 1;
    } else if (i1 > i2) {
      return -1;
    }
    return m1.group(2).compareTo(m2.group(2));
  }
}

For Collections http://java.sun.com/javase/6/docs/api/java/util/Collections.html您可以使用Collections.sort() http://download.oracle.com/javase/6/docs/api/java/util/Collections.html#sort(java.util.List,%20java.util.Comparator)

上面假设你的数组元素是Strings like "22 ASomething"而不是包含事件和一些文本的特定数据结构。如果是这种情况,您可以使用更简单的Comparator.

另外,如果你确实有一个数组String可能值得首先将其转换为已解析的对象数组,以节省过度解析元素(即某些元素将被解析多次)。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

按字母顺序对数组进行排序 的相关文章

随机推荐