简体   繁体   中英

Sorting Values based on ArrayList of Objects

I stuck with comparing values. Array List consists of two objects Name and Percentage.

public class DataModel {

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

and array list is

 List<DataModel> usageList;


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

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

    });

Example :

dataUsagePercent values in a arraylist is 2, 10, 40, 30, 50, 60, 90, 65,55,100.

i have to compare the values of dataUsagePercent . lowest should come at 0th position in arraylist and the top four categories that make up the highest value of dataUsagePercent. Additionally, the six remaining values (that make up the lowest percentage of usage) are combined into a single percentage.

Output for above values after comparing list should consists of :

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

final list size should be always 5 only and name value has no impact

Edit: Missed 60. add to combined value

I think your list data type need to change as List<DataUsageModel> usageList; to compare dataUsagePercent values you can use Collections.sort(usageList); or you can use priority queue

First, order the list by dataUsagePercent :

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

Here I'm using List.sort and Comparator.comparing methods.

Then, I'd use a common for loop to do the grouping, taking care of the index:

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

The output is [2, 245, 65, 90, 100] .

First I would sort the list:

Collections.sort(usageList, new Comparator<DataModel>(){
    public int compare(DataModel d1, DataModel d2){
        return Integer.compare(d1.getDataUsagePercent(), d2.getDataUsagePercent());
    }
});
  • After that you can just take the first element and the last 3.
  • Add the middle values together
  • And create your result array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM