VGDev
VGDev

Reputation: 303

Get the median length from an arraylist

I've very new to Java and I wanted to get a calculation but it keeps coming back wrong. I'm trying to get the median length of words added to an arraylist. I find codes to do this with arrays but I can't seem to find a solution to doing this with an arraylist.

This is my code: (individual string words are added through a text field)

ArrayList<String> stringList = new ArrayList<>();

double wordLength;
double average;
double middle;
String medianNum;

@Override
protected void onCreate(Bundle savedInstanceState) {...

    middle = 0;

    for (String word2 : stringList) {
        wordLength = stringList.length();
        middle = wordLength / 2;
    }

    if (middle % 2 == 1){
        medianNum = String.format("%.2f", middle);
    } else {
        medianNum =  String.format("%.2f", ((middle-1) + middle)/2.0);
    }

    // Add/Update the average number to the textview
    medianLength.setText(medianNum);


}

Upvotes: 1

Views: 1946

Answers (1)

hasan
hasan

Reputation: 24185

First, sort the array depending on the strings length. Can be achieved by passing the Comarator to the sort function as follow:

Collections.sort(stringList, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2)
    {
        return  s1.length() - s2.length();
    }
});

Then, get the middle as follows:

if (stringList.size() % 2 == 1) {
    middle = stringList.get(stringList.size()/2).length();
} else {
    middle = (stringList.get(stringList.size()/2).length()
           + stringList.get(stringList.size()/2-1).length()) / 2.0;
}

Upvotes: 3

Related Questions