Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an ArrayList by length of Strings in the array

I've recently begun taking a Computer Science course to understand programming more and seem to have hit a roadblock with our lab on ArrayLists. The purpose of the program is to put x amount of strings into an ArrayList and then output the results in descending order.

Ex:Zebra, Deer, Giraffe Deer

Result:Giraffe, Zebra, Deer

I've looked around online and found a few examples using ArrayList comparators but our professor wants us to do it by filtering out the largest word, printing it, removing it and then continue that loop until all words are printed out.

Here is my code so far:

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);
    int length = 0;
    String longest = "";
    String currentWord = "";
    ArrayList <String> DescendArray = new ArrayList<String>();
    System.out.println("What would you like to add to the list?");
    String userInput = input.next();
    while(!userInput.equals("d"))
    {
        DescendArray.add(userInput);
        userInput = input.next();
    }
    for (int i=0; i < DescendArray.size(); i++)
    {
        if (DescendArray.get(i).length() > longest.length())
                {
                    currentWord = DescendArray.get(i);
                    if (currentWord.length() > longest.length())
                    {
                        longest = currentWord;
                        length = longest.length();
                    }
                }
        for (int j=1; j < DescendArray.size() -1 ; j++)
        {
            if (DescendArray.get(j - 1).length() > longest.length())
            {
                DescendArray.remove(j - 1);
            }
            System.out.println(longest + " " + length);
        }
    }
}

}

I'm assuming my error is somewhere in the inner loop but I can't seem to get it to work no matter how many different variations I use.

like image 302
Nare Avatar asked Oct 30 '25 21:10

Nare


2 Answers

Try this, it works for me.

     List<String> sorted = list.stream()
                .sorted(Comparator.comparingInt(String::length))
                .collect(Collectors.toList());
like image 158
Bruce Avatar answered Nov 01 '25 10:11

Bruce


This is basically what you gotta do:

public class Zoo {

    public static void main(String[] args) {
        List<String> zoo = new ArrayList<String>();
        zoo.add("Zebra");
        zoo.add("Deer");
        zoo.add("Giraffe");
        zoo.add("Deer");
        while(!zoo.isEmpty()) {
            String bigger = "";
            for(String animal : zoo) {
                if(animal.length() > bigger.length()) {
                    bigger = animal;
                }
            }
            System.out.println(bigger);
            while(zoo.contains(bigger)) {
                zoo.remove(bigger);
            }
        }
    }

}
like image 43
Ulises Avatar answered Nov 01 '25 10:11

Ulises