gpt4 book ai didi

java - 对 Java 对象进行排序并根据属性查找相对位置

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:10:07 25 4
gpt4 key购买 nike

我有一个有趣的问题

这是对象结构

public class Testdata {
//Which is a consecutive running number i.e 1,2,3..etc
private int sequence;

//classified based on this again any random numbers
private int window;

//need to calculate
private int windowposition;

}

现在基于序列和窗口,我需要推导出相对于窗口的窗口位置

测试数据
所以对于测试数据序列/窗口

        1 / 2
2 / 3
3 / 2
4 / 3
5 / 3

预期输出

    sequence/window :   window position would be (in the same order)

1 / 2 : 1

2 / 3 : 1

3 / 2 : 2

4 / 3 : 2

5 / 3 : 3

更新:

是的,我已经实现了可比性并将列表按以下顺序排序

1 / 2
3 / 2
2 / 3
4 / 3
5 / 3

现在如何计算每个元素相对于其窗口的windowposition

最佳答案

实现 Comparable 可能是有意义的.这允许对您的对象进行排序。您可以像这样实现 compareTo(T):

int compareTo(Testdata o) {
return ((Integer)this.sequence).compareTo(o.sequence);
}

这样您的对象就可以按顺序排序。

现在将 window 1 的所有对象收集到一个 List 中,将 window 2 的对象收集到另一个列表中,等等。

HashMap<Integer, ArrayList<Testdata>> map = new HashMap<Integer, ArrayList<Testdata>>();

// Add all the objects like this
while (...) { // While there are more objects
Testdata td = ... // Get next object

List<TestData> list = map.get(td.window);
if (list == null) {
list = new ArrayList<Testdata>();
map.put(td.window, list);
}

list.add(td.sequence);
}

使用 Collections.sort(List) 对所有列表进行排序:

for (ArrayList<TestData> list : map) {
Collections.sort(list);
}

然后每个窗口都有一个列表,可通过 map.get(window) 访问。这些列表中的每一个都将具有最低 sequence 的对象作为其第一个对象,第二低的作为第二个对象等。-> 窗口位置是对象的索引 + 1。

编辑:

如果您的对象已经按窗口和顺序排序(在一个列表中),您可以这样做来分配窗口位置:

int window = 1;
int wp = 0;
for (Testdata td : list) {
if (td.window > window) {
wp = 1;
window = td.window;
} else {
wp++;
}

td.windowposition = wp;
}

关于java - 对 Java 对象进行排序并根据属性查找相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11987011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com