Reputation: 43
I am trying to compare the elements of a list I created from reading a file.
The list sizes vary from 3 up to 10 elements. I want to go over my elements in the list, compare their length (I tried doing that by String = s.length()
) it worked and I got the length of every element in the list.
How can I compare each element's length? I want to choose the closest 2 elements in length and determine their index.
For instance, if this is the input file:
ATGTCATGG
ATGCGATGGGGGTCGCCC
ATGTTT
the closest 2 strings are 3 apart in length, and their indices are 0 and 2.
public class ListTesting {
public static void main(String[] args) throws IOException {
PrintStream output = new PrintStream(System.out);
Scanner input = new Scanner(System.in);
output.print("Enter the name of the file ");
String fileName = input.nextLine();
Scanner fileInput = new Scanner(new File(fileName));
List<String> listo = new ArrayList<String>();
String token = "";
while ( fileInput.hasNext() ) {
token = fileInput.next();
listo.add(token);
}
fileInput.close();
for ( int i =0; i < listo.size(); i++) {
String components = listo.get(i);
int lengtho = components.length();
//output.println(lengtho);
}
}
}
Upvotes: 1
Views: 195
Reputation: 35106
If it's okay to change the line order, you could create a Comparator
to sort by length
public class LengthComparator implements Comparator<String> {
public int compare(String s1, String s2) {
return s1.length() - s2.length();
}
}
Use Collections.sort to sort your list by length, then you can iterate through the sorted list compare each string to the next string, and see if that's shorter than the previous shortest
int shortestIdx = 0;
int shortestDist = Math.abs(list.get(0).length() - list.get(1).length());
for (int idx = 0; idx < list.size(); idx++) {
//left this for you to fill in
}
Upvotes: 2
Reputation: 1354
You can sort your List using Collections.sort(List<T> list, Comparator<? super T> c)
where you can define your own Comparator which compare Strings in your way.
Upvotes: 1