这个数据保存在data.txt中我正在尝试编写一个可以安排的程序
18b0885 // this is the registration number, bullet points to show indentation
SS844 Parallel Algorithms // These are course taken by student
SS555 Calculus for Distributed Computing
SS501 Quantum Communication
17b0585
SS828 Problem Based Programming
SS844 Parallel Algorithms
SS567 Hacking Quantum Network
17b2582
SS567 Hacking Quantum Network
SS844 Parallel Algorithms
SS501 Quantum Communication
像这样的一大串数据,需要编写一个程序来缩短这些数据,按注册号升序排列,课程将跟随注册号。所以预期的输出是这样的。
输出遗嘱、课程名称和参加该课程样本的学生注册号:
SS501 Quantum Communication
18b0885
17b2582
SS567 Hacking Quantum Network
17b2582
17b0585
SS844 Parallel Algorithms
17b2582
17b0585
18b0885
等等,哪种方法会更容易做到这一点
它没有给出想要的答案
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
import java.util.TreeSet;
public class Sort3 {
public static void main(String[] args) throws Exception {
BufferedReader reader = new BufferedReader(new FileReader("data2018.txt"));
// Map<String, List<String>> map = new TreeMap<String, List<String>>();
Map<String, Set<String>> map = new TreeMap<String, Set<String>>();
String line = reader.readLine();//read header
while ((line = reader.readLine()) != null) {
String key = getField(line); //
// List<String> l = map.get(key);
Set<String> l = map.get(key);
if (l == null) {
// l = new LinkedList<String>();
l = new TreeSet<String>();
map.put(key, l);
}
l.add(line);
}
reader.close();
FileWriter writer = new FileWriter("sorted_numbers4.txt");
writer.write("");
// for (List<String> list : map.values()) {
// for (String val : list) {
// writer.write(val);
// writer.write("\n");
// }
// }
for (Set<string> key : map.keySet()){
//print key (subject) here
writer.write("Subject="+key+"\n");
for (Set<String> list : map.get(key)) {
for (String val : list) {
writer.write(val);
writer.write("\n");
}
}
}
writer.close();
}
private static String getField(String line) {
return line.split(",")[0];//
}
}
上面的程序输出到另一个像这样的文本文件中
SS501 Quantum Communication
SS555 Calculus for Distributed Computing
SS567 Hacking Quantum Network
SS567 Hacking Quantum Network
SS660 Genetic Computation
SS828 Problem Based Programming
SS844 Parallel Algorithms
SS876 Positronics
SS880 Quark-based Logic
17b2582
17b0585
18b0885
有什么建议可以修改以获得所需的答案吗?