简体   繁体   中英

Iterate through arraylist using data from excel file

So I have a document on excel and I have a list of data saying how many people use x or y and how many times. So basically i have a column with people ID, a column with type (x and y) then a column saying how many times the people use x or y. I want to be able to iterate through the list without changing it so as it get the number of people using each type and i want the list to be sorted in ascending order or frequency. So I wanted to use a for loop to go through the list and put an if statement inside of it saying that if x, then another for loop to be able to group them by frequency.

The actual code I have is not good but I am really stuck on that and do not really know how to proceed :

 for(int i = 0; i < type1.size(); i++){
       if(events.get(i).isX()){
           for(int j = 0; j < /*max value of the data in the list*/; j++ )
  //here list should group all common frequency
       }
       else
//do same thing but for y

Excel table eg

QUESTION

Under the assumption that you have an excel-file with three columns:

id | type | frequency

And a List representing the data of your excel-file. You might want to order your Entrys with the Collections.sort(Comparator<T>) method.

Here is an example on how you can achieve that:

Example a :

Arraylist<Row> yourList = new ArrayList();
fillListWithExlData(yourList);

for(int i = 0; i < yourList.size(); i++){
    Collections.sort(yourList, new Comparator<Row>()){
    //compares row i with the following row
    compare(Row oneRow, Row followingRow){
    //if the result is 1 =< the entry moves on higher in the list if the result is = 0 it stays on its position and if its <= -1 it moves down.
    return oneRow.getFrequenzy() - followingRow.getFrequenzy();
    }
    });
}

Notice: that you can also use the Comparator to order your "types".

Example b :

return (oneRow.getType() == followingRow.getType()) ? 0 : -1;

Or you might even want to match both, id and frequency. Then you might try this:

Example c :

return (oneRow.getType() == followingRow.getType() &&  
        oneRow.getFrequenzy() == followingRow.getFrequenzy())
        ? 0 : -1;

example a should Order a potential List:

id | type | frequency
1  |  x   |    12
2  |  y   |    10
3  |  x   |    12

into:

id | type | frequency
1  |  x   |    12
3  |  x   |    12
2  |  y   |    10

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