Java:如何使用 HashMap 根据第二列中的条件对一列的所有值求和

标签 java hashmap

我有一个 CSV 文件,其中包含大约 500,000 行和 22 列的航类数据。第五列包含每次航类的每架飞机的尾号。第 22 列包含每次飞行的飞行距离。我正在尝试对每个尾号(第 5 列)的行驶总距离(第 22 列)求和。

我创建了一个 HashMap,其中包含名为 map1 的所有数据。我创建了第二个名为 planeMileagesHashMap 来放置每个航类号及其​​总飞行距离。我使用嵌套的 if 语句遍历 map1 的每一行,并查看尾部编号是否已包含在 planeMileages 中。如果它在 planeMileages 中,那么我想添加到该键的 accumulatedMileages 中。如果不包含,我想输入 key 及其第一个距离值。

我编写的当前代码对我来说似乎是合理的,但它产生了错误的结果,输出了错误的尾号。您能看一下并让我知道我在主要方法中忽略了什么吗?谢谢!

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

请查看下面我的 CSV 文件的几行:

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

最佳答案

这是一种更 OOP 的方法。

您扩展了 HashMap 并添加了两种新方法,一种用于添加航类,另一种用于计算总距离。 这样,您就不会不断地删除修改后的值并将其添加回 HashMap 中。 您可以对此进行扩展以满足您的需求。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class Main {

    public static void main(String[] args) {
        FlightData flightData = getFlightDataFromFile();
        flightData.getDistanceTraveled("tail number");
    }

    public static FlightData getFlightDataFromFile() {
        File flightFile = new File("flights.csv");
        FlightData flightData= new FlightData();

        try {
            Scanner s = new Scanner(flightFile);
            while (s.hasNextLine()) {
                String info = s.nextLine();
                String[] piecesOfInfo = info.split(",");
                String tailNr= piecesOfInfo[4];
                Flight flight = new Flight(piecesOfInfo[6], piecesOfInfo[9], Integer.parseInt(piecesOfInfo[21]));
                flightData.addFlight(tailNr, flight);
            }
            s.close();
        } catch (FileNotFoundException e) {
            System.out.println("Cannot open: " + flightFile);
        }
        return flightData;
    }
}

class FlightData extends HashMap<String,List<Flight>> {

    void addFlight(String tailNr, Flight flight) {
        computeIfAbsent(tailNr, flights -> new ArrayList<>()).add(flight);
    }

    int getDistanceTraveled(String tailNr) {
        int distance = 0;
        for (Flight f : get(tailNr)) distance+= f.distance;
        return distance;
    }

}

class Flight {
    String from;
    String to;
    int distance;

    public Flight(String from, String to, int distance) {
        this.from = from;
        this.to = to;
        this.distance = distance;
    }
}

关于Java:如何使用 HashMap 根据第二列中的条件对一列的所有值求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60696595/

相关文章:

java - 将 Guice 依赖注入(inject)添加到 web.xml 中配置的 Servlet

java - 如何恢复 mysql 默认模式,如 sakila

java - 我可以用 Timer 对象使程序饱和吗?

java - 随机播放函数复杂性

java - 变量的原始类型在编译期间没有字段 x

java - 部署War文件到Tomcat有什么好处?

javascript - 如果 hashMap 具有相同的键名称,如何获取对象数组中的所有值

python - 在 Python 中使 SWIG 包装内置类 "hashable"

c# - 在以对象为值的 C# 哈希表中,如何返回对象值

java - 将单词存储到 Hashmap 中