假设有一个文件:
Virginia Tyler Taylor Wilson
Ohio Grant Hayes Garfield Harrison_B McKinley Taft Harding
Massachusetts Kennedy Bush_GHW
New_York VanBuren Fillmore Roosevelt_T Roosevelt_F
我需要按顺序排序,下面是我的代码:
TreeMap<String, String> map = new TreeMap<String, String>();
while (infile1.ready()){
String line = infile1.readLine();
String s = line.substring(0, line.indexOf(" "));
String p = line.substring(line.indexOf(" "));
map.put(s, p);
}
for (String p : map.keySet()){
System.out.println(p + " " + map.get(p));
}
我的输出是:
Massachusetts Kennedy Bush_GHW
New_York VanBuren Fillmore Roosevelt_T Roosevelt_F
Ohio Grant Hayes Garfield Harrison_B McKinley Taft Harding
Virginia Tyler Taylor Wilson
预期输出为:
Massachusetts **Bush_GHW Kennedy**
New_York **Fillmore Roosevelt_F Roosevelt_T VanBuren**
Ohio **Garfield Grant Harding Harrison_B Hayes McKinley Taft**
Virginia **Taylor Tyler Wilson**
唯一的区别是值的顺序,我在预期的输出中加粗它。 有没有一种快速的方法来排序String p并将其放入地图?
答案 0 :(得分:2)
你可以写短文
Arrays.sort(line.substring(line.indexOf(" ")).split(" "));
答案 1 :(得分:1)
试试这个
String[] ps = line.substring(line.indexOf(" ")).split(" ");
Arrays.sort(ps);
然后尝试将ps与p结合使用&#34; &#34 ;;
答案 2 :(得分:0)
Massachusetts **Bush_GHW Kennedy**
New_York **Fillmore Roosevelt_F Roosevelt_T VanBuren**
Ohio **Garfield Grant Harding Harrison_B Hayes McKinley Taft**
Virginia **Taylor Tyler Wilson**
In your above expected output how Bush Comes after mass..
So please explore output correctly.