更新时间:2023-11-06 19:25:22
由于您希望订购您的收藏品,我建议您使用列表
和 Collections.sort
。如果您决定采用这种方法,您仍然有两种选择:
比较器
可以作为参数传递给 sort
,或分数
类工具可比较<得分>
以下是后一种方法的示例和 ideone demo :
import java.util。*;
class Score实现可比较<得分> {
int score;
字符串名称;
公共分数(int score,String name){
this.score = score;
this.name = name;
}
@Override
public int compareTo(得分o){
返回得分< o.score? -1:得分> o.score? 1:0;
}
}
公共类测试{
public static void main(String [] args){
List< Score>得分=新的ArrayList<得分>();
scores.add(新得分(23,彼得));
scores.add(新得分(11,托尼));
scores.add(新得分(110,克莱尔));
scores.add(新分数(13,ferca));
scores.add(新得分(55,朱利安));
scores.add(新得分(13,佩德罗));
Collections.sort(得分);
}
}
How can I create a list (or some other type of container) of integer and strings pairs that allows duplicates in both pairs and can be sorted by the integer value?
I need to fill a container with names (string) and scoring (integer) pairs, the container must allow duplicated values in both name and scoring, and i need to sort this list by the scoring value.
I tried with a SortedMap but doesn't allow duplicated values:
SortedMap<Integer,String> sm=new TreeMap<Integer, String>();
sm.put(23, "Peter");
sm.put(11, "Tony");
sm.put(110, "Claire");
sm.put(13, "ferca");
sm.put(55, "Julian");
sm.put(13, "Pedro");
In this example, ferca and Pedro have the same scoring value, this is something I need to allow, but the SortedMap overwrites "ferca" with "Pedro".
What is the best container type to do this?
Since you want your collection to be ordered, I suggest you use a List
and Collections.sort
. If you decide to go for this approach you still have two options:
Comparator
that can be passed as an argument to sort
, orScore
class implement Comparable<Score>
Here is an example and ideone demo of the latter approach:
import java.util.*;
class Score implements Comparable<Score> {
int score;
String name;
public Score(int score, String name) {
this.score = score;
this.name = name;
}
@Override
public int compareTo(Score o) {
return score < o.score ? -1 : score > o.score ? 1 : 0;
}
}
public class Test {
public static void main(String[] args){
List<Score> scores = new ArrayList<Score>();
scores.add(new Score(23, "Peter"));
scores.add(new Score(11, "Tony"));
scores.add(new Score(110, "Claire"));
scores.add(new Score(13, "ferca"));
scores.add(new Score(55, "Julian"));
scores.add(new Score(13, "Pedro"));
Collections.sort(scores);
}
}