walterudoing
walterudoing

Reputation: 115

Sort a some words in a string

Assuming there is a file:

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

I need to sort it in order, and below is my code:

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));
}

My output is:

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

The expected output is:

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**

The only difference is the order in the value, where I bold it in the expected output. Is there a fast way to sort String p and puts it into the map?

Upvotes: 0

Views: 60

Answers (3)

Sunny
Sunny

Reputation: 308

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.

Upvotes: 0

user3543851
user3543851

Reputation: 176

you can write in short way

Arrays.sort(line.substring(line.indexOf(" ")).split(" "));

Upvotes: 2

andy
andy

Reputation: 1356

try this

String[] ps = line.substring(line.indexOf(" ")).split(" ");
Arrays.sort(ps);

then try combine ps to p with " ";

Upvotes: 1

Related Questions