Java: Como a soma de todos os valores de uma coluna com base nos critérios em uma segunda coluna usando HashMaps

FinDev:

Eu tenho um arquivo CSV que contém cerca de 500.000 linhas e 22 colunas de dados de voo. A 5ª coluna contém o número da cauda de cada plano para cada voo. A coluna 22 contém a distância percorrida por cada voo. Eu estou tentando resumir a distância total percorrida (coluna 22) para cada número de cauda (coluna 5).

Eu criei um HashMapcontendo todos os dados nomeados map1. Eu criei uma 2ª HashMapchamada planeMileagespara colocar cada número de voo e sua distância total percorrida em. Eu estou usando uma instrução IF aninhada passar por cada linha de map1e ver se o número de cauda já está contido no planeMileages. Se ele estiver em planeMileages, então eu quero acrescentar sobre a accumulatedMileagespara essa chave. Se não for contida, eu gostaria de introduzir a chave junto com ele do primeiro valor de distância.

O código atual que eu escrevi parece som para mim, mas ele está produzindo o resultado errado, emitir o número de cauda incorreta. Você pode por favor dar uma olhada e deixe-me saber o que eu estou com vista no meu método principal? Obrigado!

public class FlightData {

    HashMap<String,String[]>  dataMap;

        public static void main(String[] args) {

            FlightData map1 = new FlightData();
            map1.dataMap = map1.createHashMap();

            HashMap<String, Integer> planeMileages = new HashMap();
            //Filling the Array with all tail numbers
            for (String[] value : map1.dataMap.values()) {

                if(planeMileages.containsKey(value[4])) {  
                    int accumulatedMileage = planeMileages.get(value[4]) + Integer.parseInt(value[21]);
                    planeMileages.remove(value[4]);
                    planeMileages.put(value[4], accumulatedMileage);
                } 
                else {
                    planeMileages.put(value[4],Integer.parseInt(value[21]));
                }
            }


            String maxKey = Collections.max(planeMileages.entrySet(), Map.Entry.comparingByValue()).getKey();

            System.out.println(maxKey);


        }





       public HashMap<String,String[]> createHashMap() {
            File flightFile = new File("flights.csv");
            HashMap<String,String[]> flightsMap = new HashMap<String,String[]>();

            try {
            Scanner s = new Scanner(flightFile);
            while (s.hasNextLine()) {

                    String info = s.nextLine();
                    String [] piecesOfInfo = info.split(",");

                        String flightKey = piecesOfInfo[4] + "_" + piecesOfInfo[2] + "_" + piecesOfInfo[11]; //Setting the Key
                        String[] values = Arrays.copyOfRange(piecesOfInfo, 0, piecesOfInfo.length);

                        flightsMap.put(flightKey, values);


            }
            s.close();
            }


           catch (FileNotFoundException e)
           {
             System.out.println("Cannot open: " + flightFile);
           }

            return flightsMap;
        }
}

Por favor, veja algumas linhas de meu arquivo CSV abaixo:

Flights.csv

DayofMonth  DayOfWeek   FlightDate  UniqueCarrier   TailNum OriginAirportID Origin  OriginStateName DestAirportID   Dest    DestStateName   DepTime DepDelay    WheelsOff   WheelsOn    ArrTime ArrDelay    Cancelled   CancellationCode    Diverted    AirTime Distance
3   1   10/3/2016   AA  N786AA  10721   BOS Massachusetts   12478   JFK New York    556 -4  623 703 709 -6  0       0   40  187
4   2   10/4/2016   AA  N794AA  10721   BOS Massachusetts   12478   JFK New York    554 -6  615 703 712 -3  0       0   48  187
1   6   10/1/2016   AA  N783AA  12478   JFK New York    12892   LAX California  823 -7  844 1104    1111    -30 0       0   320 2475
2   7   10/2/2016   AA  N798AA  12478   JFK New York    12892   LAX California  847 17  904 1131    1159    18  0       0   327 2475
3   1   10/3/2016   AA  N786AA  12478   JFK New York    12892   LAX California  825 -5  838 1109    1131    -10 0       0   331 2475
4   2   10/4/2016   AA  N794AA  12478   JFK New York    12892   LAX California  826 -4  848 1114    1132    -9  0       0   326 2475
compensação:

Olá você pode verificar isso?

public static void main(String[] args) throws  IOException {

    Map<String, String[]> map = createMap();
    Map<String, Long> planeMileages = map
            .entrySet()
            .stream()
            .collect(Collectors.groupingBy(o -> o.getValue()[4],
                    Collectors.collectingAndThen(
                            Collectors.summarizingInt(value ->
                                    Integer.parseInt(value.getValue()[21])), IntSummaryStatistics::getSum
                    )
            ));
    String maxKey = planeMileages.entrySet().stream().max(Comparator.comparing(Map.Entry::getValue)).get().getKey();
    System.out.println("max key: "+ maxKey);
}

public static Map<String, String[]> createMap() throws IOException {
    try (BufferedReader a = Files.newBufferedReader(Paths.get("flights.csv"))) {
        return a.lines().map(s -> s.split(","))
                .collect(Collectors.toMap(piecesOfInfo -> String.join("_", piecesOfInfo[4], piecesOfInfo[2], piecesOfInfo[11]), Function.identity()));
    }
}

public static Map<String, String[]> createMapLastDupWins() throws IOException {
    try (BufferedReader a = Files.newBufferedReader(Paths.get("flights.csv"))) {
        return a.lines().map(s -> s.split(","))
                .collect(Collectors.toMap(piecesOfInfo -> String.join("_", piecesOfInfo[4], piecesOfInfo[2], piecesOfInfo[11]), Function.identity(), (strings, strings2) -> {
                    //if this helps than data is duplicated
                    return strings2;
                }));
    }
}

Acho que você gosta

Origin http://43.154.161.224:23101/article/api/json?id=292901&siteId=1
Recomendado
Clasificación