简体   繁体   English

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

[英]In Java, how do I iterate through a sublist of my ArrayList?

I have a csv file with population records for 50 states, four regions (Northeast, West, etc.), and Puerto Rico, so there are more than 50 rows of data. 我有一个csv文件,其中包含50个州,四个地区(东北,西部等)和波多黎各的人口记录,因此有50多个数据行。 I need to find the number of states with a population increase, so I don't want to check all of the rows, just 50 of them for the 50 states, the 6th element through the 56th element. 我需要找到人口增加的州的数量,所以我不想检查所有行,对于50个州,从第6个元素到第56个元素,只需检查其中的50个。 I believe a sublist of the ArrayList is the way to go, but how would I code it? 我相信要使用ArrayList的子列表,但是如何编码? This is the portion of my code I'm working on: 这是我正在处理的代码的一部分:

// 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);

Here is the rest of my code in the driver class: 这是驱动程序类中的其余代码:

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

You can also try: 您也可以尝试:

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

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

As awolfe91 mentioned, simply 正如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);

OR slice the array list as you require. 或根据需要切片数组列表。 You can write a utility like 您可以编写一个实用程序,例如

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

Check a sample code here . 在此处检查示例代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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