简体   繁体   English

如何按数组中字符串的长度对 ArrayList 进行排序

[英]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.我最近开始参加计算机科学课程以更多地了解编程,但似乎在我们的 ArrayLists 实验室遇到了障碍。 The purpose of the program is to put x amount of strings into an ArrayList and then output the results in descending order.该程序的目的是将 x 数量的字符串放入一个 ArrayList 中,然后按降序输出结果。

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.我在网上环顾四周,发现了一些使用 ArrayList 比较器的示例,但我们的教授希望我们通过过滤掉最大的单词,打印它,删除它然后继续该循环,直到打印出所有单词。

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.我假设我的错误在内部循环中的某个地方,但无论我使用多少不同的变体,我似乎都无法让它工作。

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);
            }
        }
    }

}

Try this, it works for me.试试这个,它对我有用。

     List<String> sorted = list.stream()
                .sorted(Comparator.comparingInt(String::length))
                .collect(Collectors.toList());

This seems to work.这似乎有效。 If you don't want to remove repeating animals then remove distinct() method.如果您不想删除重复的动物,请删除distinct()方法。 I omitted creation of the list.我省略了列表的创建。

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Zoo {
    public static void main(String[] args) {
        List<String> zoo = Arrays.asList("Zebra", "Deer", "Giraffe", "Deer");
        String output = zoo.stream()
                           .distinct()
                           .sorted((x, y) -> Integer.compare(y.length(), x.length()))
                           .collect(Collectors.joining(","));
        System.out.println(output);
    }
}

I'm amazed at the verbosity of other solutions.我对其他解决方案的冗长感到惊讶。 A much simpler method would be to use a stream:一个更简单的方法是使用流:

List<String> original = Arrays.asList("s1", "String 2", "ss3", "s");
List<String> sorted = original.stream()
        .sorted((s1, s2) -> s2.length() - s1.length())
        .collect(Collectors.toList());
System.out.println(sorted);

Replace "original" with your ArrayList.用您的 ArrayList 替换“原始”。

Under the assumption that duplicate words need not be removed at the same time, such that a duplicate word will be removed in order, and that the list need not be done in alphabetical order (one could sort the list first), and that thread safety is not important, I would avoid using the integer counters and checking the size.假设不需要同时删除重复的单词,这样重复的单词将按顺序删除,并且列表不需要按字母顺序排列(可以先对列表进行排序),并且线程安全并不重要,我会避免使用整数计数器并检查大小。 Instead, I would run the output loop until everything has been removed.相反,我会运行输出循环,直到所有内容都被删除。

As an example:例如:

public void doRemove()
{
    while (! descendArray.isEmpty()) {
        String longest = "";

        for (String s : descendArray) {
            if (s.length() > longest.length()) {
                longest = s;
            }
        }

        if (longest.length() > 0) {
            if (descendArray.remove(longest)) {
                System.out.println(longest + " (" + longest.length() + ")");
            }
        }
    } // while we stil have things to process
}

The problem seems to be that for each iteration in your for loop, you arrive at Giraffe as your longest word, then you're checking the rest of the list to see if it is longer than Giraffe.问题似乎是,对于 for 循环中的每次迭代,您到达 Giraffe 作为最长的单词,然后您检查列表的其余部分以查看它是否比 Giraffe 长。 Instead of what you have now, I would write something like:而不是你现在拥有的,我会写一些类似的东西:

for (int i=0; i < DescendArray.size(); i++)
{
    longest = "";
    length = longest.length();
    int longestIndex = 0;
    for (int j=1; j < DescendArray.size() -1 ; j++)
    {
        currentWord = DescendArray.get(j);
        if (currentWord.length() > longest.length())
        {
            longestIndex = j;
            longest = currentWord;
            length = longest.length();
        }
    }
    DescendArray.remove(longestIndex);
    System.out.println(longest + " " + length);
}

This nested for loop should find the longest word first, store the index and print and remove the entry at that index before it finds the next longest entry.这个嵌套的 for 循环应该首先找到最长的单词,存储索引并在找到下一个最长的条目之前打印并删除该索引处的条目。

When you say descending order are you referring to the length of the string or an alphabetical comparison?当您说降序时,您指的是字符串的长度还是字母顺序比较?

Check out how the QuickSort algorithm can be used for string sorting.查看QuickSort 算法如何用于字符串排序。 You can find information on QuickSort here您可以在此处找到有关 QuickSort 的信息

Here is another variation which can be used, but involves an extra array list:这是可以使用的另一种变体,但涉及额外的数组列表:

ArrayList<String> DescendArray = new ArrayList<>();
DescendArray.add("Monkey");
DescendArray.add("Giraffe");
DescendArray.add("Hippo");
DescendArray.add("Zebra");
DescendArray.add("Monkey");

List<String> copy = new ArrayList<>(DescendArray);

for (int i=0; i<DescendArray.size(); i++) {
    String longest = "";
    for (int j=0; j<copy.size(); j++) {
        String current = copy.get(j);
        if (current.length() > longest.length()) {
             longest = current;
        }
    }
    System.out.println(longest);
    while(copy.contains(longest)) {
        copy.remove(longest);
    }        
}

When you need to remove element from the list, iterator is a better way.当您需要从列表中删除元素时,迭代器是一种更好的方法。 See below for the code.请参阅下面的代码。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

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");
        Collections.sort(zoo,new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {          
                return o2.compareTo(o1);
            }
        });
        Iterator<String> iterator=zoo.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            iterator.remove();
        }
    }
}

To sort an ArrayList based on it's each String length, you can try:要根据每个字符串长度对 ArrayList 进行排序,您可以尝试:

private ArrayList SortwithStrlength(ArrayList templist) {
        for(int i=0;i<templist.size();i++)
        {
            for(int j=0;j<templist.size();j++)
            {
                String temp;
                if(templist.get(i).toString().length()<templist.get(j).toString().length())
                {
                    temp=templist.get(i).toString();
                    templist.set(i, templist.get(j).toString());
                    templist.set(j,temp);
                }
            }
        }
        return templist;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM