2012-12-05 8 views
1

J'ai un fichier csv avec des enregistrements de population pour 50 états, quatre régions (Nord-Est, Ouest, etc.), et Porto Rico, donc il y a plus de 50 lignes de données. J'ai besoin de trouver le nombre d'états avec une augmentation de population, donc je ne veux pas vérifier toutes les lignes, seulement 50 d'entre eux pour les 50 états, le 6ème élément à travers le 56ème élément. Je crois qu'une sous-liste de ArrayList est le chemin à parcourir, mais comment le coderais-je? Ceci est la partie de mon code, je travaille sur:En Java, comment parcourir une sous-liste de mes 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); 

Voici le reste de mon code dans la classe du pilote:

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

Répondre

0

Comme mentionné awolfe91, simplement

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

OU tranche la liste de tableau que vous avez besoin. Vous pouvez écrire un utilitaire comme

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

Vérifiez un exemple de code here.

+0

Merci. J'ai remarqué que mon fichier de données répertorie District of Columbia dans les 7ème à 57ème éléments, ce qui n'est pas un état. Comment ne pas le compter? – Grafica

+0

Modifiez simplement la plage selon les besoins. Faites simplement -1 dans l'index car les index dans le tableau commencent par 0 et les lignes dans csv que vous comptez commenceraient à partir de 1. – mtk

+0

Cela continuerait de parcourir DC – Grafica

1

Vous pouvez simplement initialiser i à 5 et cesse lorsque i == 56.

+0

Comme cela? pour (int i = 6; i <57; i ++) – Grafica

+1

Yep! Mais comme les ArrayLists sont également indexés à 0, le sixième élément sera en réalité list.get (5), donc vous devriez avoir pour (int i = 5; i <57; i ++). J'espère que cela pourra aider! – awolfe91

+0

Merci, ça aide. – Grafica

3

Vous pouvez aussi essayer:

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

Th Anks, je vais le garder à l'esprit. J'y suis allé avec les réponses d'awolfe91 et de mtk parce que c'était moins de code à changer, mais c'est à toi que je pensais à l'origine. – Grafica

+0

Y at-il des raisons techniques pour lesquelles cela ne devrait pas être la solution préférée? (sauf que depuis Java 8, ce serait un meilleur candidat pour les expressions Lambda) – BamaPookie