I am new to java.
I'm trying to sort an ArrayList of String arrays using String.compareTo().
I have compiled the code so that the output is:
Causality,is,a,relationship
It,is,also,called,causation
It,is,about,a,cause,and,its,affect
Now I want to sort that code (lexicographically) so the output is:
Causality,a,is,relationship
It,also,called,causation,is
It,a,about,affect,and,cause,is,its
However I am generating some crazy output.
My code is below.
Any help would be appreciated.
I have worked on this probably very simple problem for hours and I am ready to destroy my computer. Thanks
public class Wk5Q5 {
void process1 () {
String s1 = "Causality is a relationship";
String s2 = "It is also called causation";
String s3 = "It is about a cause and its affect";
ArrayList<String[]> list = new ArrayList<String[]>();
String[] arr1 = s1.split(" ");
list.add(arr1);
String[] arr2 = s2.split(" ");
list.add(arr2);
String[] arr3 = s3.split(" ");
list.add(arr3);
/**
* previously sorted the arraylist of string arrays so that
* each word is separated by commas
*/
for(int i = 0; i < list.size(); i++){
for (int j = 0; j < list.get(i).length; j++){
String t = list.get(i)[j];
if (j > 0){
t = ", " + t;
}
System.out.print(t);
//System.out.println(list.get(i)[j]);
}
System.out.println();
}
/**
* my attempt at sorting each string in each list
*/
for(int z = 0; z < list.size(); z++){
for(int i = 0; i < list.get(z).length; i++){
String x = list.get(z)[i];
for (int j = i+1; j < list.get(z).length; j++){
String y = list.get(z)[j];
if(y.compareTo(x) < 0) {
String temp = list.get(z)[i];
x = list.get(z)[j];
y = temp;
}
System.out.print(x);
}
}
}
}
Collections.sort(myList)?