in java i have an array list of strings formatted as follows each entry
12,Vanilla granola bar,91.
how can i sort the list in increasing order of the first numbers of each string? would collections.sort() be able to do this?
would collections.sort() be able to do this?
Yes, but, you would need a custom Comparator in order to extract the leading values and compare them appropriately
This is a VERY basic example of the concept...
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class CustomSorter {
public static void main(String[] args) {
List<String> values = new ArrayList<>(25);
values.add("12,Vanilla granola bar,91");
values.add("1,Vanilla granola bar,91");
values.add("50,Vanilla granola bar,91");
values.add("25,Vanilla granola bar,91");
values.add("13,Vanilla granola bar,91");
dump(values);
Collections.sort(values, new SplitComparator());
dump(values);
}
protected static void dump(List<String> values) {
System.out.println(values);
}
public static class SplitComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
int i1 = getIndex(o1);
int i2 = getIndex(o2);
return i1 - i2;
}
protected int getIndex(String o1) {
return Integer.parseInt(o1.split(",")[0]);
}
}
}
It should be noted that there are simply so many things that could go wrong it's not funny. I've made no checks to determine it either of the Strings to be compared actually meet the requirements of the Comparator, nor do I handle cases where the first element is not a number for example.
A better solution would be to wrap you String values into a POJO or interface and provide appropriate appropriate getters. This would allow you to restrict the Comparator to a specific type of class, making it safer