按子列表的值对LIst列表进行排序

2 java sorting collections list

private List<String> subList;
private List<List<String>> records = new ArrayList<List<String>>();

for(....){

    subList = new ArrayList<String>();
    ...populate..
    records.add(subList);
}
Run Code Online (Sandbox Code Playgroud)

例如,subList有三个字符串--a,b和c.我想通过subList中的b值对记录进行排序.

records at 0 has a list of "10", "20", "30"
records at 1 has a list of "10", "05", "30"
records at 2 has a list of "10", "35", "30"
Run Code Online (Sandbox Code Playgroud)

排序后,记录的顺序应为 -

records at 0 = records at 1 above
records at 1 = records at 0 above
records at 2 = records at 2 above
Run Code Online (Sandbox Code Playgroud)

什么可能是一个很好的算法呢?

eri*_*son 5

这就像排序一串字符一样:给定两个字符串,从头开始并比较每个字符; 如果存在差异,则具有较低值的字符串首先出现,否则,请查看每个字符串中的下一个字符.如果字符串具有不同的长度,则将较短的字符串视为具有零后缀.

在这种情况下,"字符"是通过调用获得的整数值Integer.parseInt().此外,实现一个Comparatorfor List<String>将在这里有所帮助.然后Collections.sort()可以使用该方法.

比较器看起来像这样:

final class MyComparator implements Comparator<List<String>> {

  public int compare(List<String> a, List<String> b) {
    /* Assume all strings are parseable to values 
     * in range [0,Integer.MAX_VALUE] */
    int len = Math.min(a.size(), b.size());
    for (int idx = 0; idx < len; ++idx) {
      int va = Integer.parseInt(a.get(idx)), vb = Integer.parseInt(b.get(idx));
      if (va != vb)
        return va - vb;
    }
    return va.size() - vb.size();
  }

  @Override
  public boolean equals(Object o) {
    return o instanceof MyComparator;
  }

  @Override
  public int hashCode() {
    return MyComparator.class.hashCode();
  }

}
Run Code Online (Sandbox Code Playgroud)

  • 根据上下文,使用封装类替换`List <String>`也许值得. (2认同)

Kev*_*ose 5

就像是:

Collections.sort(records, new Comparator<List<String>>()
{
  public int compare(List<String> o1, List<String> o2)
  {
    //Simple string comparison here, add more sophisticated logic if needed.
    return o1.get(1).compareTo(o2.get(1));
  }
})
Run Code Online (Sandbox Code Playgroud)

虽然我发现在实践中对位置进行硬编码有点可疑,但您的意见可能会有所不同.