Reeggiie Reeggiie - 3 months ago 26
Java Question

How to compute smallest string in ArrayList using Comparator?

I need to write a static method in a class MinTester that computes the "smallest" string
from an ArrayList collection using a comparator object:

public static String min(ArrayList<String> list, Comparator<String> comp)


I cannot use the Collections class to compute the minimum.

Here is what I have so far.

public class MinTester
{

static String least;//This is static because it is being used in a static static context


public static String min(ArrayList<String> list, Comparator<String> comp)
{
int min = 0;


for( int i = 0; i < list.size(); i++ )
{
min = list.get(i).compareTo(list.get(i++));
if(min < 0)
{
least = list.get(i);
}
else if(min == 0)
{
least = list.get(i);
}
else
{
least = list.get(i++);
}
}
return least;
}
}


I am using the min value because I read that the compareTo method returns negative, 0, or positive whether the first string is less than, equal to, or greater than the second.

I am not getting any errors here from the method, So I try to test it in Main with this.
I get this warning: "Accessing static method min"

public static void main(String[] args)
{
// TODO code application logic here

MinTester s = new MinTester();
Comparator<String> comp = null;
ArrayList<String> list = new ArrayList<>();

list.add("a");
list.add("ab");
list.add("abc");
list.add("abcd");

String a = s.min(list,comp);//Warning: Accessing static method min

System.out.println(a);
}


My output from a = "abcd". Can anyone help me figure out why I am getting "abcd" as the 'Min' string in the list? I am thinking that my error is coming from my min() method, but I am not sure where inside it or why.

Answer

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.

Comments