在java中对相关文本文件进行排序创建公共索引
大家好 我想对 2 个相关文件进行排序,创建一个可以对它们进行排序的唯一索引
我有一个格式如下示例的 .txt 文件:
File1
Houston
Chicago
Seattle
Cleveland
另一个文件的格式如下:
File2
44
33
55
22
我想要以下输出:
Seattle 55
Houston 44
Chicago 33
Cleveland 22
我创建了 2 个数组.txt 文件中的对象,因此由于“< 或 >”,我无法使用冒泡排序操作员。我使用 .sort 函数对分数进行排序,但通过这种方式,我不会创建索引来对团队进行排序。我该如何解决这个问题?
这是我的代码
private void visualizzaClassificaButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
List<String> teams = new ArrayList<String>();
List<Float> scores = new ArrayList<Float>();
try {
FileInputStream fstream = new FileInputStream("C:/Users/Fra....../file1");
FileInputStream fstream2 = new FileInputStream("C:/Users/Fra...../file2");
DataInputStream in = new DataInputStream(fstream);
DataInputStream in2 = new DataInputStream(fstream2);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String team = null;
String score = null;
while ((score = br.readLine()) != null && (team = br2.readLine()) !=null) {
teams.add(team);
scores.add(Float.parseFloat(score));
}
Object[] squadreTutte = teams.toArray();
Object[] punteggiTutti = scores.toArray();
Arrays.sort(punteggiTutti, Collections.reverseOrder());
//????????????????????????????????
for(int index=0; index<punteggiTutti.length; index++){
System.out.println(punteggiTutti[index]);
System.out.println(squadreTutte[index]);
}
in.close();
} catch (Exception e) {
}
}
请帮忙
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
几乎总是当有人想要对并行数组进行排序时,就会发生 拒绝对象。
您应该做的是创建一个对象来保存名称,分数对:
然后,在读取文件时,为文件中的每一行创建一个
Team
对象,将它们放入收集并排序。您需要实现
Comparable
在你的班级中(就像我上面所做的那样)或提供Comparator
对它们进行排序。Almost always when someone wants to sort parallel arrays, it's a case of object denial.
What you should be doing is to create an object to hold the name,score pair:
Then, when reading the files, create a
Team
object for each line in the files, put them into aCollection
and sort that. You either need to implementComparable
in your class (as I did above) or provide aComparator
to sort them.在自然语言中对球队和得分进行排序并以相反的顺序读取集合要简单得多。顺便说一句,除非有充分的理由,否则不要使用 float 或 Float。使用 Long 或 Double 代替。
基于@Joachim 的团队课程
It is a lot simpler to sort the team and score in natrual worder and read the collection is reverse order. BTW Don't use float or Float unless there is a really good reason to do so. Using Long or Double instead.
Based on @Joachim's Team class
目标是第一个列表中的球队按第二个列表中的分数排序?
您的问题是两个列表的排序不相关。您应该尝试对情侣进行“团队+得分”排序。也许使用
List>
之类的东西可以通过定义自定义比较器来完成您想要的操作......The goal is that the teams in the first list are sorted by score from the second list ?
Your problem is that the sorting of both lists are unrelated. You should try instead to sort the couples "team+score". Maybe using something like a
List<Entry<Double, String>>
could do what you want by defining a custom comparator...