gpt4 book ai didi

Java 按特定顺序放入树形图

转载 作者:搜寻专家 更新时间:2023-11-01 01:17:59 25 4
gpt4 key购买 nike

我有一个大列表并将其放入树状图中。

然后我想把“ALL”放在列表的最顶部,但是在“ALL”之前有一个“AAA”

编辑:我希望对所有其他输入进行排序

List     ->    List
----- -----
AAA AAA
BBB ALL
CCC BBB
CCC

我可以使用 arrayList 或其他东西,但我想知道如果有办法控制这种情况。

最佳答案

一个选择是构建一个自定义比较器,它始终将“ALL”一词排在其他所有内容之前:

TreeMap<String, T> myMap = new TreeMap<String, T>(new Comparator<String>() {
public int compare(String lhs, String rhs) {
/* See which of the inputs, if any, are ALL. */
bool oneAll = lhs.equals("ALL");
bool twoAll = rhs.equals("ALL");

/* If both are ALL or neither are ALL, just do a normal comparison. */
if (oneAll == twoAll) {
return lhs.compareTo(rhs);
}
/* Otherwise, exactly one of them is ALL. Determine which one it is and
* react accordingly.
*/
else if (oneAll) {
return -1;
} else {
return +1;
}
}
});

这将按升序对所有内容进行排序,但优先考虑 “ALL” 高于其他所有内容。

希望这对您有所帮助!

关于Java 按特定顺序放入树形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11002609/

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