按字符串或索引的一部分对字符串数组进行排序?

时间:2016-10-17 05:17:49

标签: java arrays eclipse sorting mergesort

我已经编写了这个程序,我按字母顺序对字符串数组进行排序。我希望能够通过数字字符串的不同部分对其进行排序。 (我也在使用eclipse)。 这就是我所拥有的:

import edu.princeton.cs.algs4.Merge;

public class sortNum {

    public static void main(String[] args) {
    // TODO Auto-generated method

    String[] age = {"Meredith Chicago #82", 
            "Brian Phoenix #45", "Jess Miami #26", 
            "Gunther NYC #53", "Frank Boise #4"};

    System.out.println("-----------------------------");

    //loop through array and print out unsorted string

    for(String i : age){
        System.out.printf("%25s\n", i); //to right-align

    }

    System.out.println("-----------------------------");

    Merge.sort(age);

    //loop through array and print sorted string

    for(String j: age){
        System.out.println(j); //this is where I am unsure of the right way
    }



    System.out.println("-----------------------------");
  }

}

对于输出,我得到了这个:

-----------------------------
     Meredith Chicago #82
        Brian Phoenix #45
           Jess Miami #26
          Gunther NYC #53
           Frank Boise #4
-----------------------------
Brian Phoenix #45
Frank Boise #4
Gunther NYC #53
Jess Miami #26
Meredith Chicago #82
-----------------------------

显然这是因为它看着字符串的开头。这不是问题,当然也不是预期的。

我可以将它设置为查看数字的位置吗?可以通过计算索引来完成吗?例如,从最后(#)索引算起但不包括-1并按此排序?升序当然。我仍然希望使用for循环。

通过为每条信息创建单独的对象,我将在没有循环的情况下使用它,但后来意识到这将需要永远,而且会有太多的代码。

2 个答案:

答案 0 :(得分:3)

我建议你为这类数据创建单独的对象:

public class User implements Comparable<User> {
  private int mId;
  private String mName;

  public User(final int id, final String name) {
    mId = id;
    mString = name;
  }

  public String getName() {
    return mName;
  }

  @Override
  public int compare(final User lhs, final User rhs) {
    return Integer.compare(lhs.mId, rhs.mId);
  }

  @Override
  public String toString() {
    return String.format("%s #%d", mName, mId);
  }
}

这里我实现了Comparable<User>,您可以根据需要覆盖比较类型。在这里,我只是比较id上的用户。 在此之后,您可以根据需要使用Collections.sort(List<User>)Merge.sort(Comparable[]),然后对其进行排序。此外,覆盖toString()方法可以简单地将用户信息输出为user.toString()

答案 1 :(得分:1)

您可以使用Arrays.sort对数组进行排序,并为其提供自定义比较器。例如,使用Java 8:

Arrays.sort(age, Comparator.comparingInt(a -> Integer.parseInt(a.split("#")[1])));

虽然这段代码有效,但我建议创建一个类来封装逻辑。

public class Person {
    public static Person decode(String line) {
        Matcher matcher = Pattern.compile("(\\w+) #(\\d+)").matcher(line);
        if (!matcher.matches())
            throw new IllegalArgumentException("Illegal format");
        return new Person(matcher.group(1), matcher.group(2));
    }

    public int getAge() {...}
    public String getName() {...}
}

然后使用流,您的代码可以变得更加明确:

Arrays.stream(age)
    .map(Person::decode)
    .sorted(Comparator.comparingInt(Person::getAge))
    .forEach(...);