簡體   English   中英

排序ArrayList <String[]> 按字母順序

[英]Sorting an ArrayList<String[]> in alphabetical order

我是Java的新手,想知道如何按字母順序對String []類型的ArrayList進行排序。 在這種情況下,我的ArrayList名稱是temp。 基本上,String []將包含3個元素:字符串a,字符串b和字符串c。 我想相對於字符串a對數組列表進行排序。 我正在使用Java 10。

我已經嘗試過了,但是沒有用

ArrayList<String[]> temp = somefunction();
Collections.sort(temp);

這是顯示的錯誤:

sort(java.util.List<T>) in Collections cannot be applied 
      to(java.util.ArrayList<java.lang.String[]>)

方法Collections.sortT參數化,這意味着條件<T extends Comparable<? super T>> <T extends Comparable<? super T>>應該很滿意。 String[]不滿足要求,因為它沒有擴展Comparable

Collections.<String[]>sort(new ArrayList<>());
Collections.<String>sort(new ArrayList<>());

當我們想對不可比較的值進行排序時Collections.sort(List, Comparator)我們利用Collections.sort(List, Comparator)

Collections.sort(new ArrayList<>(), (String[] a1, String[] a2) -> 0);
Collections.<String[]>sort(new ArrayList<>(), (a1, a2) -> 0);

當然,您應該將模擬比較器(String[] a1, String[] a2) -> 0 (將所有元素都視為相同)替換為真實的比較器。

這里的問題是您沒有嘗試對字符串列表進行排序(例如,“ cat”小於“ dog”)。 您正在嘗試對字符串數組列表進行排序。

array [“ cat”,“ dog”]小於array [“ dog”,“ cat”]嗎? 該邏輯默認情況下不存在,您必須對其進行定義。

范例程式碼

這是一個示例(嚴重地只是使用第一個元素):

public static void main(String[] args) {
    List<String[]> s = new ArrayList<>();
    s.add(new String[] {"dog", "cat"});
    s.add(new String[] {"cat", "dog"});
    s.sort((o1, o2) -> {
        //bad example, should check error conditions and compare all elements.
        return o1[0].compareTo(o2[0]);
    });

    //Outputs [cat, dog] then [dog, cat].
    s.forEach(x -> System.out.println(Arrays.toString(x)));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM