java - 根据两个条件对列表进行排序

标签 java android sorting

所以,我不知道是否有一个优雅的解决方案,但这里是。我想对列表进行排序,但该列表包含三种类型的项目。我想要的是类型 A 按字母顺序排列在顶部,类型 B 和 C 位于底部并按字母顺序排列(类型 B 和 C 将合并)。

这是我的代码:

public int compareTo(Friendship another) {
    if(this.getType().equals(TypeA) &&
            another.getType().equals(TypeA)){ //if they are both type A, just sort based on user name

        return this.getUsername().compareTo(
                another.getUsername());
    }
    else if(this.getType.equals(TypeA)){ 
        return -1;
    }
    else if(another.getType().equals(TypeA)){
        return 1;
    }
    else{ //this will be hit if they are either Type B or C, then just sort based on username
        return this.getUsername().compareTo(
                another.getUsername());
    }
}

编辑:抱歉,我应该更好地解释这一点。问题是上面的代码不起作用。据我所见,该列表似乎没有正确排序。 <罢工> 由于某种原因,TypeA 列表的顺序与我想要的相反(Z -> A)。而 TypeB & C 列表只排序了一半。所以我假设我的代码中存在错误。如果您需要更多信息,请告诉我。

EDIT2:对样本进行了更多测试,看起来字符串根本没有被排序。我都做了

this.getUsername().compareTo(
            another.getUsername());

another.getUsername().compareTo(
            this.getUsername());

编辑 3:你们是对的。我的代码中的其他地方有一个错误(这是不相关的)。抱歉......在这种情况下也不知道该怎么办。我该给谁正确的答案?

最佳答案

如果我是你,我不会改变结构,只会优化这点

public int compareTo(Friendship another) {


       if(!this.getType().equals(another.getType()){
        //if type are not equal, so we might have at most one A

          if(this.getType.equals(TypeA)){ //on left side
             return -1;
          }

          if(another.getType().equals(TypeA)){ //or, on rightside
            return 1;
          }
        }
          //or we have on both sides or neither side
            return this.getUsername().compareTo(
                    another.getUsername());
        }

关于java - 根据两个条件对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28159148/

相关文章:

java - 将 JSON 数据解析为类

java - Switch 语句只返回最后一个 case

android.hardware.action.NEW_PICTURE 被触发了两次

java - 对表进行排序会破坏 TableRowListener?

java - Collections.sort() 不排序单个数字

python - 在 Python 2.3 中按最后 N 个字符对字符串列表进行排序

java - 什么是类的参数化调用

java - 在 Clojure 中导入 Lucene jar

java - 如何正确导入类: Http Client from Apache Commons

android - 使用 Gradle 在 Android Studio 中运行普通 Java 项目的单元测试