java - 同时对两个数组列表进行排序

标签 java arrays sorting arraylist comparator

假设我有两个 ArrayLists:

name: [Four, Three, One, Two]
num:  [4, 3, 1, 2]

如果我这样做:Arrays.sort(num),那么我有:

name: [Four, Three, One, Two]
num:  [1, 2, 3, 4]

有什么办法可以对 num 进行排序并将其也反射(reflect)在名称中,这样我可能会得到:

name: [One, Two, Three, Four]
num:  [1, 2, 3, 4]

?请帮帮我。我想到了比较器和对象,但对它们几乎一无所知。

最佳答案

您应该以某种方式关联 namenum 字段到一个类中,然后拥有该特定类的实例列表。在此类中,提供一个检查数值的 compareTo() 方法。如果您对实例进行排序,那么名称字段也将按您希望的顺序排列。

class Entity implements Comparable<Entity> {
    String name;
    int num;
    Entity(String name, int num) {
        this.name = name;
        this.num = num;
    }
    @Override
    public int compareTo(Entity o) {
        if (this.num > o.num)
            return 1;
        else if (this.num < o.num)
            return -1;
        return 0;
    }
}

测试代码可以是这样的:

public static void main(String[] args) {
    List<Entity> entities = new ArrayList<Entity>();
    entities.add(new Entity("One", 1));
    entities.add(new Entity("Two", 2));
    entities.add(new Entity("Three", 3));
    entities.add(new Entity("Four", 4));
    Collections.sort(entities);

    for (Entity entity : entities)
        System.out.print(entity.num + " => " + entity.name + " ");
}

输出:

1 => One 2 => Two 3 => Three 4 => Four

关于java - 同时对两个数组列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17780398/

相关文章:

java - 如何从 JSONObject 获取所有数组?

java - GSON反序列化复杂对象数组

arrays - 如何在 Rust 的构造函数中创建数组

python - Quichesort 的好处

sorting - 如何根据 haskell 中另一个向量的排序顺序对向量值进行重新排序?

c++是否有默认数据类以合理的速度进行基于排序索引的访问?

java - 如何在 Spring 中使用单个 @Bean 注释方法(或类似方法)注册多个 bean?

java - 由于服务类错误,Spring Boot 应用程序未启动

java - 如何指定 'this' 指的是什么?

c++ - 'C' 程序 : multidimensional array issue