Reputation: 21
I'm reading in a file line by line and I need sort lines alphabetically, for example, in the below example, it should sort by first letter of each word and output it. I'm stuck on how to sort it by first character of each word alphabetically and retain the numbers in front of each word. Any help is appreciated. Thanks in advance.
output: 567 cat
123 dog
FILE2 = "123 dog\n567 cat\n";
String args[] = {"-a", "5", inputFile.getPath()};
String expected = 567 cat
123 dog
I've tried reading in the lines and sorting but it sorts based on the numbers first.
if (arguments.equals("-a")) {
List<String> lines = Files.readAllLines((Paths.get(filename)));
List<String> matchedLines = lines.stream().sorted()
.collect(Collectors.toList());
Upvotes: 2
Views: 177
Reputation: 1249
You could do something like following( take a note I didn't put anything in file, you could get string out of file easily as you already did ). Following code assumes you have got string from your file:
public static void main(String[] args) {
//what we have got from file
String text = "123 dog\n567 cat\n";
//split text to substrings by new line
String[] splitted = text.split("\n");
// create treemap and sort it from greatest to lowest number
Map<Integer, String> mapOfStrings = new TreeMap<Integer, String>().descendingMap();
//put all substrings into our map, following assumes a form that first substring is a text and second substring is an integer
for (int i = 0; i < splitted.length; i++) {
mapOfStrings.put(Integer.valueOf(splitted[i].substring(0, splitted[i].indexOf(" "))), splitted[i].substring(splitted[i].indexOf(" "), splitted[i].length()));
}
//iterate thru map, for each entry in it print its key and value in single line
for (Map.Entry<Integer, String> entry : mapOfStrings.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
UPDATE 2:
If you would like to sort by letters( from a to z ) following code would suffice:
public static void main(String[] args) {
String text = "123 dog\n567 cat\n4 zebra\n1983 tiger\n1 lion\n383 turtle";
String[] splitted = text.split("\n");
System.out.println(Arrays.asList(splitted));
Map<String, Integer> mapOfStrings = new TreeMap<String, Integer>();
for (int i = 0; i < splitted.length; i++) {
mapOfStrings.put(splitted[i].substring(splitted[i].indexOf(" "), splitted[i].length()),Integer.valueOf(splitted[i].substring(0, splitted[i].indexOf(" "))));
}
for (Map.Entry<String, Integer> entry : mapOfStrings.entrySet()) {
System.out.println(entry.getValue()+ " " + entry.getKey());
}
}
Upvotes: 2