簡體   English   中英

我該如何按其中包含的一些整數對ArrayList進行排序?

[英]How should I sort an ArrayList by some integers contained in it?

顯然這不是我的工作,而是一個例子。 我已經使用Comparable,compareTo,compare,Collections,sort等進行了兩個多小時的工作。這不涉及對其進行排序附加在其上的字符串,但是第一個數字應堅持其各自的詞。 ArrayList必須保持原樣,但就我所知,我已經用盡了所有其他可能性。

    6 Worda
    8 Wordb
    7 Wordc
    20 Wordd
    2 Worde
    5 Wordf
    1 Wordg
    10 Wordh
    1 Wordi
    2 Wordj

新的ArrayList類似於:

    1 Wordi
    1 Wordg
    2 Wordj
    2 Worde
    5 Wordf
    6 Worda
    8 Wordb
    7 Wordc
    10 Wordh
    20 Wordd
  1. 創建一個帶有字段的類來保存每一行的信息(這里是一個int和一個String),
  2. 使類與自身可比。 例如,如果該類稱為MyClass,則使其實現Comparable<MyClass>
  3. 給它一個體面的compareTo(...)方法
  4. 在此方法中,應首先按數字字段排序,如果數字不相等,則返回一個值。
  5. 然后按String秒(如果兩個數字相等)。

你說

顯然這不是我的工作,而是一個例子。

如果您需要更多特定的幫助,請考慮發布您的實際代碼以及應該保留的實際數據。


編輯您的帖子:

public int compareTo(Team o) { 
   if (this.apps >= o.apps) { 
     return this.apps; 
   } else { 
     return o.apps; 
   } 
} 

請解釋一下。


例如

// assuming Team has an int field, score and a String field, name
public int compareTo(Team o) { 
  if (Integer.compare(score, o.score) != 0) {
    // the scores are not the same, so return the comparison
    return Integer.compare(score, o.score)
  } else {
    // the scores are the same, so compare the Strings:
    return name.compareTo(o.name);
  } 
} 

除了@Hovercraft答案以外,另一種排序方式是。 無需定義自然排序 (使用Comparable),而是創建自己的排序策略(使用Comparator)。

創建一個保存數據的類

public class MyClass{

private String s;
private Integer id;
public static final Comparator MY_COMPARATOR = new MyComparator();

public MyClass(String s, Integer id){
    this.s=s;
    this.id=id;
}

@Override
public String toString(){
  return "ID :"+id+" property: "+s;
}

//Add getter&setter if you need    

//static nested class
private static class MyComparator implements Comparator<MyClass>{
      @Override
      public int compareTo(MyClass c, MyClass c2){
           //check possible nullPointerException
           int result = c.id.compareTo(c2.id);
           if(result == 0){
              return c.s.compareTo(c2.s);
           }
           return result;
      }

}

}

然后在客戶端代碼中

List<MyClass> list = new ArrayList<>();
 //add data to the list

 //print it before sort
 System.out.println(list); 
 Collections.sort(list,MyClass.MY_COMPARATOR);
 //print it after sorting
 System.out.println(list);

從您的示例看來,您想要使用以下規則對每個元素進行排序:

  1. 最低人數
  2. 如果數字相等,則為最高字符串(即降序排列)

所以您的可比對象應該在其中,例如(偽代碼)

if (me (number) < other (number) then me is less than
else if (me (number > other <number the me is greater than
else if (me (word) > other (word) then me is less than
else if (me (word) < other (word) then me is greater than
else me equals other

暫無
暫無

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

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