package parseInteresting.complete; import com.opencsv.bean.CsvToBean; import com.opencsv.bean.CsvToBeanBuilder; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.util.*; /** * This class is part of a demo to demonstrate how csv data can be parsed using Java * This class uses the CSVReader to read a CSV file and read the file line by line * This part of the demo will use UfoSightingModel.java and will create an object for each line * The created objects will then be used to look at aggregate data trends and information */ public class UfoDataParser { /** * The path of the csv from the root */ private static final String CSV_FILENAME = "ufo-data.csv"; /** * Reads the csv file and analyzes the aggregate data * * @param args */ public static void main(String[] args) { InputStream stream = UfoDataParser.class.getResourceAsStream("/data/" + CSV_FILENAME); if(stream == null) { System.err.println("File not found: " + CSV_FILENAME); System.exit(1); } Reader reader = new BufferedReader(new InputStreamReader(stream)); // CsvToBean csvToBean = new CsvToBeanBuilder(reader) .withType(UfoSightingModel.class) .withIgnoreLeadingWhiteSpace(true) .build(); Iterator csvUserIterator = csvToBean.iterator(); Map stateUfoObservations = new HashMap<>(); while(csvUserIterator.hasNext()) { UfoSightingModel ufoSightingRecord = csvUserIterator.next(); String country = ufoSightingRecord.getCountry(); if(!country.equals("us")) { continue; } String state = ufoSightingRecord.getState(); if(!stateUfoObservations.containsKey(state)) { stateUfoObservations.put(state, 0); } stateUfoObservations.put(state, stateUfoObservations.get(state) + 1); } Map> observationsToStateReverseOrdered = new TreeMap<>(Collections.reverseOrder()); for(String state : stateUfoObservations.keySet()) { int observations = stateUfoObservations.get(state); if(!observationsToStateReverseOrdered.containsKey(observations)) { observationsToStateReverseOrdered.put(observations, new HashSet<>()); } observationsToStateReverseOrdered.get(observations).add(state); } System.out.println(observationsToStateReverseOrdered); } }