在Java中,如何遍历ArrayList的子列表?

时间:2012-12-05 21:01:09

标签: java netbeans arraylist sublist

我有一个csv文件,其中包含50个州,四个地区(东北,西部等)和波多黎各的人口记录,因此有超过50行数据。我需要找到人口增加的状态数,所以我不想检查所有行,只有50个状态用于50个状态,第6个元素到第56个元素。我相信ArrayList的子列表是要走的路,但是我该怎么编码呢?这是我正在处理的代码部分:

// Number of states with estimated population increase in 2011
            int x = 0;
         // al = arrayList.subList(6,56);
            for (int i = 0; i < popList.size(); i++) {
                PopulationRecord pr1 = popList.get(i);
                if (pr1.getPopch2011() > 0) {
                    x++;
                }
            }
            System.out.println("Number of states with estimated population increase in 2011 is " + n);

以下是我在驱动程序类中的其余代码:

package miniproj2;

import domain.PersistentObject;
import domain.PopulationRecord;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import utilities.MiniProj2Utilities;
import domain.CensusComparator;

/**
 *
 * @author
 */
public class MiniProj2Driver {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {

        // Make sure that you develop your main() method with reduced code as shown below. 
        // Not the use of private static methods in the driver called from main() method.

        // Read the CSV file records into a list of PopulationRecord objects...
        List<PopulationRecord> popList = MiniProj2Utilities.getDataRecords();

        // Display the list contents and size...
        MiniProj2Utilities.displayRecordsFromList(popList);

        // Create and populate the PersistentObject...
        PersistentObject po = MiniProj2Utilities.getPersistentObject(popList);
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./data/population-record.ser"));
            oos.writeObject(po);
        } catch (IOException ex) {
        }

        long serializedTime = System.currentTimeMillis();

        System.out.println(po);

        try {
            Thread.sleep(5000);
        } catch (InterruptedException ex) {
            System.out.println("Sleep Error");
        }
        try {
            ObjectInputStream oos = new ObjectInputStream(new FileInputStream("./data/population-record.ser"));
            PersistentObject po1 = (PersistentObject) oos.readObject();
        } catch (IOException ex) {
        } catch (ClassNotFoundException ex) {
        }
        System.out.println("Time waited is: " + (serializedTime - System.currentTimeMillis()) / 1000 + " secs.");

        // Maximum births for 2010 and 2011
        PopulationRecord max = popList.get(0);
        for (int i = 0; i < popList.size(); i++) {
            if (CensusComparator.compareBirths(max, popList.get(i)) == 1) {
                max = popList.get(i);
            }
        }
        System.out.println("Maximum births for 2010 is " + max.getBirths2010());
        System.out.println("Maximum births for 2011 is " + max.getBirths2011());

        // Minimum births for 2010 and 2011
        PopulationRecord min = popList.get(0);
        for (int i = 0; i < popList.size(); i++) {
            if (CensusComparator.compareBirths(min, popList.get(i)) == -1) {
                min = popList.get(i);
            }
        }
        System.out.println("Minimum births for 2010 is " + min.getBirths2010());
        System.out.println("Minimum births for 2011 is " + min.getBirths2011());

        // Population % increase per region for 2010
        for (int i = 0; i < popList.size(); i++) {
            PopulationRecord pr1 = popList.get(i);

            float inc = 0;

            if (pr1.getName().equals("Northeast Region")) {
                inc = ((float) pr1.getPopch2010() / (float) pr1.getPopest2010()) * 100;
                System.out.println("Estimated population increase for 2010 in Northesast Region is " + inc);
            } else if (pr1.getName().equals("Midwest Region")) {
                inc = ((float) pr1.getPopch2010() / (float) pr1.getPopest2010()) * 100;
                System.out.println("Estimated population increase for 2010 in Midwest Region is " + inc);
            } else if (pr1.getName().equals("South Region")) {
                inc = ((float) pr1.getPopch2010() / (float) pr1.getPopest2010()) * 100;
                System.out.println("Estimated population increase for 2010 in South Region is " + inc);
            } else if (pr1.getName().equals("West Region")) {
                inc = ((float) pr1.getPopch2010() / (float) pr1.getPopest2010()) * 100;
                System.out.println("Estimated population increase for 2010 in West Region is " + inc);
            }
        }

        // Population % increase per region for 2011
        for (int i = 0; i < popList.size(); i++) {
            PopulationRecord pr1 = popList.get(i);

            float inc = 0;

            if (pr1.getName().equals("Northeast Region")) {
                inc = ((float) pr1.getPopch2011() / (float) pr1.getPopest2011()) * 100;
                System.out.println("Estimated population increase for 2011 in Northesast Region is " + inc);
            } else if (pr1.getName().equals("Midwest Region")) {
                inc = ((float) pr1.getPopch2011() / (float) pr1.getPopest2011()) * 100;
                System.out.println("Estimated population increase for 2011 in Midwest Region is " + inc);
            } else if (pr1.getName().equals("South Region")) {
                inc = ((float) pr1.getPopch2011() / (float) pr1.getPopest2011()) * 100;
                System.out.println("Estimated population increase for 2011 in South Region is " + inc);
            } else if (pr1.getName().equals("West Region")) {
                inc = ((float) pr1.getPopch2011() / (float) pr1.getPopest2011()) * 100;
                System.out.println("Estimated population increase for 2011 in West Region is " + inc);
            }
        }

        // Number of states with estimated population increase in 2010
        int n = 0;
        for (int i = 0; i < popList.size(); i++) {
            PopulationRecord pr1 = popList.get(i);

            if (pr1.getPopch2010() > 0) {
                n++;
            }
        }
        System.out.println("Number of states with estimated population increase in 2010 is " + n);

        // Number of states with estimated population increase in 2011
        int x = 0;
        al = arrayList.subList(6,56);
        for (int i = 0; i < popList.size(); i++) {
            PopulationRecord pr1 = popList.get(i);
            if (pr1.getPopch2011() > 0) {
                x++;
            }
        }
        System.out.println("Number of states with estimated population increase in 2011 is " + n);

        // Number of states with estimated population decrease in 2010
        int y = 0;
        for (int i = 0; i < popList.size(); i++) {
            PopulationRecord pr1 = popList.get(i);

            if (pr1.getPopch2010() < 0) {
                y++;
            }
        }
        System.out.println("Number of states with estimated population decrease in 2010 is " + y);

        // Number of states with estimated population decrease in 2011
        int z = 0;
        for (int i = 0; i < popList.size(); i++) {
            PopulationRecord pr1 = popList.get(i);

            if (pr1.getPopch2011() > 0) {
                z++;
            }
        }

        System.out.println("Number of states with estimated population decrease in 2011 is " + z);

        // State with highest estimated population decrease for 2010 
        PopulationRecord max3 = popList.get(6);
        for (int i = 6; i < popList.size(); i++) {
            if (CensusComparator.comparePop2010(max3, popList.get(i)) == 1) {
                max3 = popList.get(i);
            }
        }
        System.out.println("State with highest estimated population for 2010 is " + max3.getName());

        // State with highest estimated population increase for 2011 
        PopulationRecord max4 = popList.get(6);
        for (int i = 6; i < popList.size(); i++) {
            if (CensusComparator.comparePop2011(max4, popList.get(i)) == 1) {
                max4 = popList.get(i);
            }
        }
        System.out.println("State with highest estimated population for 2011 is " + max4.getName());

        // State with lowest estimated population increase for 2010 
        PopulationRecord min2 = popList.get(6);
        for (int i = 6; i < popList.size(); i++) {
            if (CensusComparator.comparePopul2010(min2, popList.get(i)) == 1) {
                min2 = popList.get(i);
            }
        }
        System.out.println("State with lowest estimated population for 2010 is " + min2.getName());

        // State with lowest estimated population increase for 2011 
        PopulationRecord min3 = popList.get(6);
        for (int i = 6; i < popList.size(); i++) {
            if (CensusComparator.comparePopul2011(min3, popList.get(i)) == 1) {
                min3 = popList.get(i);
            }
        }
        System.out.println("State with lowest estimated population for 2011 is " + min3.getName());

    }

    // Read the CSV file records into a list of PopulationRecord objects...
    private static List<PopulationRecord> getDataRecords() {
        BufferedReader br = null;
        String line = null;
        List<PopulationRecord> list = new ArrayList<PopulationRecord>();
        try {
            br = new BufferedReader(new FileReader("data/NST_EST2011_ALLDATA.csv"));
            br.readLine(); // Remove header line from file...
            while ((line = br.readLine()) != null) {
                String[] tokens = line.split(",");
                //System.out.println(line);            
                PopulationRecord pr = new PopulationRecord(
                        tokens[0], tokens[1], tokens[2], tokens[3], tokens[4],
                        Integer.parseInt(tokens[5]), Integer.parseInt(tokens[6]),
                        Long.parseLong(tokens[7]), Long.parseLong(tokens[8]),
                        Long.parseLong(tokens[9]), Long.parseLong(tokens[10]),
                        Long.parseLong(tokens[11]), Long.parseLong(tokens[12]),
                        Long.parseLong(tokens[13]), Long.parseLong(tokens[14]),
                        Long.parseLong(tokens[15]), Long.parseLong(tokens[16]),
                        Long.parseLong(tokens[17]), Long.parseLong(tokens[18]),
                        Long.parseLong(tokens[19]), Long.parseLong(tokens[20]),
                        Long.parseLong(tokens[21]), Long.parseLong(tokens[22]),
                        Long.parseLong(tokens[23]), Float.parseFloat(tokens[24]),
                        Float.parseFloat(tokens[25]), Float.parseFloat(tokens[26]),
                        Float.parseFloat(tokens[27]), Float.parseFloat(tokens[28]),
                        Float.parseFloat(tokens[29]));
                list.add(pr);
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(MiniProj2Driver.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MiniProj2Driver.class.getName()).log(Level.SEVERE, null, ex);
        }
        return list;
    }

    // Display the list contents and size...
    private static void displayRecordsFromList(List<PopulationRecord> list) {
        for (PopulationRecord record : list) {
            System.out.println(record);
        }
        System.out.println("Population records processed: " + list.size() + list.get(9));

    }

    private static PersistentObject getPersistentObject(List<PopulationRecord> list) {
        PersistentObject po = new PersistentObject();
        po.setSerializedTime(new Date());
        po.setPopulationList(list);
        return po;
    }
}

3 个答案:

答案 0 :(得分:4)

您也可以尝试:

for(PopulationRecord pr1 : popList.subList(5, 56)) {
    if (pr1.getPopch2011() > 0) {
        x++;
    }
}

答案 1 :(得分:1)

您可以简单地将i初始化为5,并在i == 56时停止。

答案 2 :(得分:0)

正如awolfe91所述,只是

// Number of states with estimated population increase in 2011
int x = 0;
// al = arrayList.subList(6,56);
for (int i = 5; i < popList.size(); i++) {
    if(i == 56) break;
    PopulationRecord pr1 = popList.get(i);
    if (pr1.getPopch2011() > 0) {
        x++;
    }
}
System.out.println("Number of states with estimated population increase in 2011 is " + n);

根据需要对数组列表进行切片。您可以编写像

这样的实用程序
public static <T> List<T> slice(List<T> list, int index, int count) {
    List<T> result = new ArrayList<T>();
    if (index >= 0 && index < list.size()) {
    int end = index + count < list.size() ? index + count : list.size();
        for (int i = index; i < end; i++) {
                result.add(list.get(i));
         }
    }
    return result;
}

检查示例代码here