gpt4 book ai didi

java - 基于两个元素使用比较器在Java列表中进行嵌套排序

转载 作者:行者123 更新时间:2023-11-30 08:59:36 26 4
gpt4 key购买 nike

我有一个 java 列表,我需要在向其中添加对象后对其进行排序。该对象具有三个元素。一个字符串和两个整数。该类如下:-

public class ValueWords implements Comparable<ValueWords>{

//.............................................

public static final Comparator<ValueWords> valComparator = new Comparator<ValueWords>()
{@Override
public int compare(ValueWords v1, ValueWords v2) {
return v1.valWord - v2.valWord; }
}
};
//....................................................................
private String strWord;
private int valWord;
private int phraseWord;
public int getPhraseWord() {
return phraseWord;}
public void setPhraseWord(int phraseWord) {
this.phraseWord = phraseWord;}
public String getStrWord() {
return strWord;}
public void setStrWord(String strWord) {
this.strWord = strWord;}
public int getValWord() {
return valWord;}
public void setValWord(int valWord) {
this.valWord = valWord;}
public ValueWords() {}

@Override
public int compareTo(ValueWords arg0) {
// TODO Auto-generated method stub
return 0;}
//..............................................
}

我是这样调用它的

 Collections.sort(valWordList,ValueWords.valComparator);

它给我排序后的列表如下:-

 ---------------------------------------------
strWord valWord phraseWord
abcd 0 1
abcde 0 0
mns 1 2
efgh 1 1
xyz 2 2
zxx 2 0
--------------------------------------------

我想要一个嵌套排序:-

  ---------------------------------------------
strWord valWord phraseWord
abcde 0 0
abcd 0 0
efgh 1 1
mns 1 2
zxx 2 0
xyz 2 2
--------------------------------------------

我做了一些徒劳的尝试,但对 Java 还是个新手。他们没有工作。将它们放在这里很安静。

最佳答案

尝试更改比较器以检查两个值:

public static final Comparator<ValueWords> valComparator = new Comparator<ValueWords>() {
@Override
public int compare(ValueWords v1, ValueWords v2) {
if(v1.valWord == v2.valWord)
return v1.phraseWord - v2.phraseWord;
else
return v1.valWord - v2.valWord;
}
};

关于java - 基于两个元素使用比较器在Java列表中进行嵌套排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27151960/

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