Since all the values are stored in the Map
as String
s separated by space, you will have to post-process the Map
(ie, process it after you've finished reading it)...
Basically, I would extract each value, split them on the space character into a String[]
and use Arrays#sort
to sort them. Reproduce the String
value and set it back as the value for the specified key.
For example...
for (String name: map.keySet())
{
String key = name.toString();
String value = map.get(name).toString();
String[] parts = value.split(" ");
Arrays.sort(parts);
StringBuilder sb = new StringBuilder(value.length());
for (String part : parts) {
if (sb.length() != 0) {
sb.append(" ");
}
sb.append(part);
}
map.put(key, value);
}
It might be easier to start with a SortedMap<String, SortedSet<String>>
. That way you could sort the values as your are reading the file, but you'd have to still post process the file to generate the SortedMap<String, String>
map you are using.
This, of course, assumes that there are no duplicates values ;)
If there are duplicate values, you could use SortedMap<String, List<String>>
instead. But you would need to post process the map after you finish loading it, using something Collections.sort(List) to sort the List
associated with each key in the Map
and produce the String
value you want...
SortedSet example
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("datasone.txt"));
Map<String, SortedSet<String>> map = new TreeMap<String, SortedSet<String>>();
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String[] pair = currentLine.split("\\s+");
String key = pair[0];
String value = pair[1];
SortedSet<String> set = map.get(key);
if (set == null) {
set = new TreeSet<String>();
map.put(key, set);
}
set.add(value);
}
for (String name : map.keySet()) {
String key = name.toString();
SortedSet<String> set = map.get(key);
StringBuilder sb = new StringBuilder(128);
sb.append(key).append(":");
for (String value : set) {
sb.append(" ").append(value);
}
System.out.println(sb.toString());
}
} catch (IOException exp) {
exp.printStackTrace();
} finally {
try {
reader.close();
} catch (Exception e) {
}
}
Which reads...
A1BG G5730
A1BG A4527
A1BG E3732
A1BG B0166
BCA3 C1478
BCA3 A4172
BCA3 D8974
BCA3 B1432
BCA3 E2147
DB8C N0124
DB8C K7414
DB8C X9851
And generates...
A1BG: A4527 B0166 E3732 G5730
BCA3: A4172 B1432 C1478 D8974 E2147
DB8C: K7414 N0124 X9851