如何创建整数和字符串对的排序列表? [英] How can I create a sorted list of integer and string pairs?
问题描述
如何创建整数和字符串对的列表(或其他类型的容器),允许两对中的重复项并且可以按整数值排序?
<我需要用名称(字符串)和评分(整数)对填充容器,容器必须允许名称和评分中的重复值,并且我需要按评分值对此列表进行排序。
我尝试使用SortedMap但不允许重复值:
SortedMap< Integer,串GT; sm = new TreeMap< Integer,String>();
sm.put(23,彼得);
sm.put(11,Tony);
sm.put(110,Claire);
sm.put(13,ferca);
sm.put(55,朱利安);
sm.put(13,Pedro);
在这个例子中,ferca和Pedro具有相同的得分值,这是我需要允许的,但是SortedMap用Pedro覆盖ferca。
这样做的最佳容器类型是什么?
由于您希望订购您的收藏品,我建议您使用列表
和 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:
- Create a custom
Comparator
that can be passed as an argument tosort
, or - Let the auxiliary
Score
class implementComparable<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);
}
}
这篇关于如何创建整数和字符串对的排序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!