簡體   English   中英

如何按數組中字符串的長度對 ArrayList 進行排序

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

我最近開始參加計算機科學課程以更多地了解編程,但似乎在我們的 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);
        }
    }
}

}

我假設我的錯誤在內部循環中的某個地方,但無論我使用多少不同的變體,我似乎都無法讓它工作。

這基本上是你必須做的:

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

}

試試這個,它對我有用。

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

這似乎有效。 如果您不想刪除重復的動物,請刪除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);
    }
}

我對其他解決方案的冗長感到驚訝。 一個更簡單的方法是使用流:

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 替換“原始”。

假設不需要同時刪除重復的單詞,這樣重復的單詞將按順序刪除,並且列表不需要按字母順序排列(可以先對列表進行排序),並且線程安全並不重要,我會避免使用整數計數器並檢查大小。 相反,我會運行輸出循環,直到所有內容都被刪除。

例如:

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
}

問題似乎是,對於 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 循環應該首先找到最長的單詞,存儲索引並在找到下一個最長的條目之前打印並刪除該索引處的條目。

當您說降序時,您指的是字符串的長度還是字母順序比較?

查看QuickSort 算法如何用於字符串排序。 您可以在此處找到有關 QuickSort 的信息

這是可以使用的另一種變體,但涉及額外的數組列表:

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

當您需要從列表中刪除元素時,迭代器是一種更好的方法。 請參閱下面的代碼。

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

要根據每個字符串長度對 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