If you need to find the shortest String
in an ArrayList
without sorting it, you can simply traverse the list and check the .length
attribute of every String
, always keeping track of the shortest one.
String shortest = list.get(0);
for(String str : list) {
if (str.length() < shortest.length()) {
shortest = str;
}
}
System.out.println("The shortest string: " + shortest);
EDIT :
You would use Comparator
if you wanted to implement custom comparison of two strings. Comparing their length can be done in 1 line, so Comparator
is really not necessary. If you absolutely need to use the Comparator
, you would replace
if (str.length() < shortest.length())
by
if (comp.compare(str, shortest) < 0))
it's basically the same thing, except that you don't define the comparison by yourself but leave it up to the Comparator
to decide, which String
of the two is smaller. This way, if you wanted the way how the strings are compared in the future, you wouldn't have to rewrite the method, you would only supply a different Comparator
.