java排序问题

标签 java sorting

我有一个 POJO 的数组列表,其中的数据采用以下形式

id    time
2     467
3     403
4     602
3     529
5     398

要求是,首先我需要按时间对数据进行排序,然后相同的 ID 应该一个接一个,即

id     time
5      398
3      403
3      529
2      467
4      602.

最初为了按时间排序,我使用以下逻辑

Collections.sort(list, new Comparator<Asset>() {
                    @Override
                    public int compare(Asset o1, Asset o2) {

                        if (o1.getTime() > o2.getTime())

                            return -1;

                        else if (o1.getTime() < o2.getTime())

                            return 1;

                        else

                            return 0;

                    }

                });

有人可以帮助我在下一阶段通过 ID 进行俱乐部吗?

最佳答案

要根据您提供的示例对数据进行排序,您可能需要对列表进行两次遍历。 (您还如何确定 3 504 应该出现在 5 315 之前还是之后?)

  1. 按照时间排序。
  2. 根据每个 ID 的第一个索引对列表进行排序。

这是一些示例代码:

import java.util.*;

class Asset {
    public int id;
    public int time;

    public Asset(int id, int time) {
        this.id = id;
        this.time = time;
    }

    public String toString() {
        return id + "  " + time;
    }
}


class Test {
    public static void main(String[] args) {

        List<Asset> assets = new ArrayList<Asset>();
        assets.add(new Asset(2, 467));
        assets.add(new Asset(3, 403));
        assets.add(new Asset(4, 602));
        assets.add(new Asset(3, 529));
        assets.add(new Asset(5, 398));

        // Sort according to time.
        Collections.sort(assets, new Comparator<Asset>() {
            @Override
            public int compare(Asset o1, Asset o2) {
                return new Integer(o1.time).compareTo(o2.time);
            }
        });

        // Remember the original indexes of each asset.
        final List<Asset> assetsCopy = new ArrayList<Asset>(assets);

        // Sort the collection based on the index of the first asset
        // with the same id
        Collections.sort(assets, new Comparator<Asset>() {

            private int firstIndexOf(int id) {
                for (int i = 0; i < assetsCopy.size(); i++)
                    if (assetsCopy.get(i).id == id)
                        return i;
                return -1;
            }

            @Override
            public int compare(Asset o1, Asset o2) {
                return new Integer(firstIndexOf(o1.id))
                        .compareTo(firstIndexOf(o2.id));
            }
        });


        for (Asset a : assets)
            System.out.println(a);
    }
}

输出:

5  398
3  403
3  529
2  467
4  602

关于java排序问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9767103/

相关文章:

java - 在 Java 中使用扫描线算法的最近点对

java - 从特定列索引开始遍历数组

java - JAXB:对具有相同值的不同 XML 元素进行解码

java - 滥用 ragel,可能需要新的方法/工具

java - 按类列的值按升序对 Parse 集合进行排序

sorting - GWT 数据网格滚动到排序的最后一列

ruby-on-rails - 按另一个 id 数组对 activerecord 结果集进行排序

sorting - Elasticsearch基于多个字段的排序

java - 原子整数 : keep non-negative

java - Java 是否会优化函数调用以消除运行时不必要的 boolean 比较?