[英]Sorting Values based on ArrayList of Objects
我堅持比較價值觀。 數組列表由兩個對象Name和Percentage組成。
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()));
}
});
示例:
arriylist中的dataUsagePercent值為2, 10, 40, 30, 50, 60, 90, 65,55,100.
我必須比較dataUsagePercent
的值。 最低位置應位於arraylist中的第0位,前4位類別構成dataUsagePercent的最高值。 此外,剩余的六個值(構成最低使用百分比)合並為一個百分比。
比較列表后的上述值的輸出應包括:
2,10+30+40+50+55+60,65,90,100 means 2, 245,65,90,100
最終列表大小應始終為5,名稱值不會產生任何影響
編輯:錯過60.添加到組合值
我認為您的列表數據類型需要更改為List<DataUsageModel> usageList;
比較dataUsagePercent值你可以使用Collections.sort(usageList);
或者您可以使用優先級隊列
首先,按dataUsagePercent
對列表進行dataUsagePercent
:
usageList.sort(
Comparator.comparing(
DataModel::getDataUsagePercent,
Comparator.comparingInt(Integer::parseInt)));
這里我使用的是List.sort
和Comparator.comparing
方法。
然后,我將使用一個通用的for循環來進行分組,處理索引:
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]
。
首先,我會對列表進行排序:
Collections.sort(usageList, new Comparator<DataModel>(){
public int compare(DataModel d1, DataModel d2){
return Integer.compare(d1.getDataUsagePercent(), d2.getDataUsagePercent());
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.