2017-04-20 134 views
1

我堅持比較值。數組列表由兩個對象名稱和百分比組成。基於對象的ArrayList排序值

public class DataModel { 

    private String name; 
    private String dataUsagePercent; 
    int color; 
} 

和數組列表是

List<DataModel> usageList; 


Collections.sort(usageList, new Comparator<DataModel>(){ 
     public int compare(DataModel d1, DataModel d2){ 

      return (d1.getDataUsagePercent()) - Integer.parseInt(d2.getDataUsagePercent())); 
     } 

    }); 

實施例:

在一個數組列表dataUsagePercent值是2, 10, 40, 30, 50, 60, 90, 65,55,100.

我必須的值進行比較的dataUsagePercent。最低應該在數組使用數組中最高的第0個位置和構成dataUsagePercent最高值的前四個類別 。此外,剩餘的六個值(構成使用率的最低百分比) 合併爲一個百分比。

輸出上面值進行比較後的清單應該包括:

2,10+30+40+50+55+60,65,90,100 means 2, 245,65,90,100 

最終名單的大小應該始終僅5和名稱值沒有任何影響

編輯:錯過60.添加到組合值

+0

您可以創建另一個ArrayList並將所有百分比的副本放入其中,然後使用'Collections.sort(arraylist)'。然後抓住四個最高和最低值,並添加其餘的。這是假定名稱對百分比沒有影響。 – Misys

+0

您需要實現Comparable才能使用Collections.sort –

+0

[This](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List - )? – Misys

回答

0

我認爲您的清單數據類型需要更改爲List<DataUsageModel> usageList; 以比較dataUsagePercent值,您可以使用Collections.sort(usageList); 或者您可以使用priority queue

0

首先,dataUsagePercent訂購列表:

usageList.sort(
    Comparator.comparing(
     DataModel::getDataUsagePercent, 
     Comparator.comparingInt(Integer::parseInt))); 

這裏我使用List.sortComparator.comparing方法。

然後,我會使用一個常見的循環來分組,走索引的護理:

int[] topFive = new int[5]; 

int size = usageList.size(); 
for (int i = 0; i < size; i++) { 
    int value = Integer.parseInt(usageList.get(i).getDataUsagePercent()); 
    if (i == 0) { 
     topFive[0] = value; // lowest value at the beginning 
    } else if (i > 0 && i < size - 3) { 
     topFive[1] += value; // accumulate intermediate values in 2nd position 
    } else { 
     topFive[i - size + 5] = value; // top values in the last 3 positions 
    } 
} 

輸出爲[2, 245, 65, 90, 100]

0

首先我想對列表進行排序:

Collections.sort(usageList, new Comparator<DataModel>(){ 
    public int compare(DataModel d1, DataModel d2){ 
     return Integer.compare(d1.getDataUsagePercent(), d2.getDataUsagePercent()); 
    } 
}); 
  • 那之後,你可以只取第一個元素和最後3
  • 添加中間值加在一起
  • 並創建結果數組