【问题标题】:How to sort an ArrayList by length of Strings in the array如何按数组中字符串的长度对 ArrayList 进行排序
【发布时间】:2016-03-29 18:29:17
【问题描述】:

我最近开始学习计算机科学课程以进一步了解编程,并且似乎在我们的 ArrayLists 实验室遇到了障碍。该程序的目的是将x个字符串放入一个ArrayList中,然后按降序输出结果。

例如:斑马、鹿、长颈鹿 鹿

结果:长颈鹿、斑马、鹿

我在网上四处查看,发现了一些使用 ArrayList 比较器的示例,但我们的教授希望我们通过过滤掉最大的单词、打印它、删除它然后继续循环直到打印出所有单词来做到这一点。

到目前为止,这是我的代码:

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

}

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

【问题讨论】:

  • “我假设我的错误出现在内部循环中” - 错误是什么?是不编译,抛出异常,还是给出不正确的结果?
  • 代码编译正常,下面是输入输出示例: 输入:Giraffe, Hippo, Zebra 输出:Giraffe, Giraffe, Giraffe
  • 是否需要删除重复的单词?在您的示例中,鹿只在输出中写入一次。

标签: java for-loop arraylist while-loop


【解决方案1】:

这基本上就是你要做的:

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

}

【讨论】:

  • 您可能应该为每次移除打印动物,根据他的预期输出,应该打印每次移除。
  • 根据他的帖子-> 结果:长颈鹿、斑马、鹿
  • @Ulises,不仅忍者我的答案很好,而且使用基本相同的算法......
  • @KevinO,他的答案比你早 2 分钟发布!
  • @JamesWierzba,是的,他在我的答案出现之前发布了,但是我在编辑器中写作,然后在我提交答案后收到了 hist 发布的通知。不仅是时机问题,而且是使用 .isEmpty() 方法而不是我感兴趣的循环。归功于更快的打字员。
【解决方案2】:

我对其他解决方案的冗长感到惊讶。一个更简单的方法是使用流:

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

用您的 ArrayList 替换“原始”。

【讨论】:

    【解决方案3】:

    试试这个,它对我有用。

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

    【讨论】:

    • 但是这个列表不包含相同的字符串吗?似乎问题只想打印一次“鹿”。
    【解决方案4】:

    这似乎有效。如果您不想删除重复的动物,请删除 distinct() 方法。我省略了列表的创建。

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

    【讨论】:

      【解决方案5】:

      假设不需要同时删除重复的单词,这样重复的单词将按顺序删除,并且列表不需要按字母顺序排列(可以先对列表进行排序),并且线程安全并不重要,我会避免使用整数计数器并检查大小。相反,我会运行输出循环,直到所有内容都被删除。

      举个例子:

      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
      }
      

      【讨论】:

        【解决方案6】:

        当您说降序时,您是指字符串的长度还是按字母顺序比较?

        查看QuickSort algorithm 如何用于字符串排序。你可以找到information on QuickSort here

        【讨论】:

        • 我指的是字符串的长度,所以它会从最长的字符串到最低的排序
        【解决方案7】:

        问题似乎在于,对于 for 循环中的每次迭代,您到达 Giraffe 作为最长的单词,然后您正在检查列表的其余部分以查看它是否比 Giraffe 长。而不是你现在拥有的,我会写这样的东西:

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

        这个嵌套的 for 循环应该首先找到最长的单词,存储索引并在找到下一个最长的条目之前打印并删除该索引处的条目。

        【讨论】:

          【解决方案8】:

          这是另一个可以使用的变体,但涉及一个额外的数组列表:

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

          【讨论】:

          • 这非常有效,并为我提供了所需的确切输出!我的问题是我的 for 循环做错了事,但添加了第二个 ArrayList 来比较事物,这肯定有助于找出我的问题所在 非常感谢您的帮助!
          • 很高兴有帮助!请记住,这不是最有效的解决方案,因为它使用了额外的列表。 @Ulises 建议的一种更有效的方法。
          【解决方案9】:

          当您需要从列表中删除元素时,迭代器是一种更好的方法。代码见下文。

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

          【讨论】:

            【解决方案10】:

            要根据每个字符串的长度对 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;
                }
            

            【讨论】:

              猜你喜欢
              • 2011-11-26
              • 2015-10-16
              • 2011-03-11
              • 2010-10-18
              • 2012-12-24
              • 2016-04-23
              • 1970-01-01
              • 1970-01-01
              • 2015-01-16
              相关资源
              最近更新 更多